Set focus to embedded MSHTML - mshtml

In my application I have an embedded MSHTML control. The problem is that I cannot set focus to this control. I can click, select, push buttons etc, but it won't accept keyboard input and mouse wheel notifications as a result. Even left-clicks on the control do not set the focus. (The question is related to this issue.)
Ultimately, I've tried 4 approaches. (Error handling is omitted here for brevity.) The first is sending WM_SETFOCUS to the control.
HWND iehwnd = ::FindWindowEx (m_oleObjectHWND, NULL,
L"Shell DocObject View", NULL);
if(iehwnd != NULL)
{
iehwnd = ::FindWindowEx (iehwnd, NULL, L"Internet Explorer_Server", NULL);
if(iehwnd != NULL)
{
::PostMessage(iehwnd, WM_SETFOCUS, (WPARAM)GetHWND(), NULL);
}
}
Using Winspector, I made sure that the messages came through to the control's window, but it seems to ignore them.
The second is calling the focus() method of IHtmlWindow2.
IHTMLDocument2* pHTMLDoc2 = NULL;
m_webBrowser->get_Document((IDispatch**)&pHTMLDoc2);
IHTMLWindow2* pWindow = 0;
pHTMLDoc2->get_parentWindow(&pWindow);
pWindow->focus();
This time, I get E_FAIL from focus().
MSDN says that the call may fail when the document hasn't loaded, but pHTMLDoc2->get_readyState() returns "complete". So this isn't the case.
The third is doing the UIACTIVATE verb.
hret = m_oleObject->DoVerb(OLEIVERB_UIACTIVATE, NULL,
clientSite, 0, (HWND)GetHWND(), &posRect);
This seems to achieve nothing.
The fourth is calling focus() of IHtmlDocument4.
IDispatch* pdisp = NULL;
m_webBrowser->get_Document((IDispatch**)&pdisp);
IHTMLDocument4* pHTMLDoc4 = NULL;
pdisp->QueryInterface(IID_IHTMLDocument4, (void**)(&pHTMLDoc4));
pHTMLDoc4->focus();
Does nothing.
I've spent a full day on this already and know google's links by heart now :) Hoping for a hint from experts.

Finally found it.
This function in my code (or rather the IEHtmlWin component for the wxWidgets library) returned S_FALSE. I changed the return code to S_OK - and voila...
HRESULT FS_IOleInPlaceSiteWindowless::RequestUIActivate()
{
return S_OK;
}

Related

MAUI Text Entry on Complete not Working - Possible Work around?

I'm trying to use text entry on maui to fire an event when completed. I have set the "Completed" event to a handler and it works correctly on windows. But on Android I have no joy, the event just isn't firing.
I realise there is a bug in Maui which is preventing this. But it looks like the problem was discovered in August? It's a fairly basic thing, well at least it appears to be on the face of things.
What is the best work around for this? The only thing I can think is by using the textchanged event instead of completed. This works correctly, but then i have to bodge it by doing this sort of thing:
if (entry1.Text.EndsWith("#"))
{
//Then string is complete, so need to fire correct event
System.Diagnostics.Debug.WriteLine("Complete String Detected");
}
This works and I can use it since I'm awaiting for input from a barcode scanner, so I can set the last terminating character to whatever I want. In this case I set it to a #. I can't figure out a way to detect the return key being pressed.
Thanks
Andrew
There is a similar issue on the github about the Entry.Completed and Entry.ReturnCommand not executed.
This comment shows the cause and the workaround about this problem.
detect the return key being pressed
In addition, I can't understand the problem. I have created a sample to test. The Entry.Completed event will call when I pressed the enter key. I don't kown the return key you mentioned is what. But you can use the IOnKeyListener for the android to detect any key being pressed.
Create a Listener class in the /Platform/Android:
public class MyKeyListener : Java.Lang.Object, IOnKeyListener
{
public bool OnKey(global::Android.Views.View v, [GeneratedEnum] Keycode keyCode, KeyEvent e)
{
var edittext = v as AppCompatEditText;
if (keyCode == Keycode.Enter && e.Action == KeyEventActions.Down )
//I used the Entry key as the example, you can use any other key you want to replace it.
{
edittext.ClearFocus();
edittext.SetBackgroundColor(Color.GreenYellow);
return true;
}
return false;
}
And in the page.xml:
<Entry Completed="Entry_Completed" x:Name="entry"/>
Set the listener to the entry by overriding the OnHandlerChanged() in the page.cs:
protected override void OnHandlerChanged()
      {
            base.OnHandlerChanged();
#if ANDROID
(entry.Handler.PlatformView as AndroidX.AppCompat.Widget.AppCompatEditText).SetOnKeyListener(new MauiAppTest.Platforms.Android.MyKeyListener());
#endif
}
You can also set the listener with the handler. Finally, you can try both the method above and the workaround in the issue on the github.

MS Word VSTO Addin Find.Execute fires ContentControlOnEnter event

It seems that if Find.Execute finds a result inside a ContentControl, it will cause the ContentControlOnEnter and ContentControlOnExit events to fire. It's particularly annoying because the exit event fires even if the selection is still in the content control, so any code which sets the states of buttons dependent upon a content control being active will appear to be in the incorrect state.
Given a document containing a single content control with the word "test", and the following code:
// In setup
Application.ActiveDocument.ContentControlOnEnter += ActiveDocument_ContentControlOnEnter;
private void ActiveDocument_ContentControlOnEnter(Word.ContentControl ContentControl)
{
var selRange = _Application.Selection.Range;
_logger.Debug(m => m("Selection: {0}-{1}", selRange.Start, selRange.End));
}
//Later in another method
var finder = _Application.ActiveDocument.Range().Find;
_logger.Debug("Find.Execute start");
finder.Execute("test);
_logger.Debug("Find.Execute end");
The following gets logged:
38137 [VSTA_Main] DEBUG - Find.Execute start
38141 [VSTA_Main] DEBUG - Selection: 1-5
38149 [VSTA_Main] DEBUG - Find.Execute end
We have a lot of code that handles ContentControlOnEnter and ContentControlOnExit events, and having the find operation cause them to be called is really causing problems!
Is there any way to use Find.Execute without having it trigger these events? Failing that, is there a good way to distinguish between the Find-triggered ones and the genuine user ones? I have tried using the time between the enter and exit events, but this is not reliable.
I had similar problems in Word, though it was about the Selection event. I tried many solutions, but only one helped. In your case, make a new field bool _skipEnterAndExitEvents and set it true before calling
finder.Execute("test) and false after calling. And in the enter and exit event handlers check this field, if the field is true then just skip. This solutions is not beautiful, looks like a hack, but other solutions are even uglier and don't really work.
I think I found a decent solution:
private bool _doIgnoreNextExit = false;
private void ActiveDocument_ContentControlOnEnter(Word.ContentControl ContentControl)
{
if (Application.Selection.Find.Found)
{
_logger.Debug("Ignoring CC enter event caused by Find operation");
_doIgnoreNextExit = true;
return;
}
// Do things
}
private void ActiveDocument_ContentControlOnExit(Word.ContentControl ContentControl)
{
if(_doIgnoreNextExit)
{
_logger.Debug("Ignoring fake exit");
_doIgnoreNextExit = false;
return;
}
// Do things
}

gtkentry focus behaviour

Is there any existing mechanism for a GtkEntry to simply position the cursor at the end of the text when focused, rather than selecting its contents to be overwritten by the next key? It seems odd to have to add a signal handler to do something this basic, but I can't find anything in the properties.
Edit: The signal handler doesn't work; whatever I do the default behaviour gets triggered after my handler runs. Here's my gtkd code; note that I am appending some text in the focus-in-event handler, and the appended text gets selected as well:
class NoteView : Entry
{
this(string text) {
if (text) {
setText(text);
}
setEditable(true);
setCanFocus(true);
addOnFocusIn(delegate bool(GdkEventFocus* f, Widget w) {
// clear selection
selectRegion(0, 0);
// test to see whether the appended text gets selected too
appendText("hello");
setPosition(-1);
// don't let any other handlers run
return 1;
}, ConnectFlags.AFTER);
}
}
The addOnFocusIn method is in the gtkd Gtk.Widget api; it calls g_signal_connect_data internally, which should in theory be honouring the G_CONNECT_AFTER flag I'm passing it, but doesn't seem to be.
Edit2: Solved - the grab-focus handler was doing the text selection, and being handled after focus-in-event
Turns out GtkEntry was selecting the text on the grab-focus signal, not focus-in-event. Working code:
class NoteView : Entry
{
this(string text) {
if (text) {
setText(text);
}
setEditable(true);
setCanFocus(true);
setHasFrame(false);
addOnGrabFocus(delegate void(Widget w) {
selectRegion(0, 0);
setPosition(-1);
}, ConnectFlags.AFTER);
}
}
Can't find anything in the docs.
I guess they figured that diverging from the default behavior is that uncommon that they just let people do it with signals, rather than provide a property for it.
Consider creating a subclass of GtkEntry that exhibits the behavior you require.

Mobile Safari: Disable scrolling pages "out of screen"

I want to block scrolling page "out of the iPhone screen" (when gray Safari's background behind the page border is visible). To do this, I'm cancelling touchmove event:
// Disables scrolling the page out of the screen.
function DisableTouchScrolling()
{
document.addEventListener("touchmove", function TouchHandler(e) { e.preventDefault(); }, true);
}
Unfortunately, this also disables mousemove event: when I tap on a button then move my finger out of it, then release the screen, the button's onclick event is triggered anyway.
I've tried mapping touch events on mouse events, as desribed here: http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/, but to no avail (the same behavior).
Any ideas?
From what I understand of your question, you've attempted to combine the code you've presented above with the code snippet provided by Ross Boucher on Posterous. Attempting to combine these two snippets back-to-back won't work, because in disabling touchmove, you've also disabled the shim that allows mousemove to work via his sample.
This question and its answers sketch out a workable solution to your problem. You should try these two snippets to see if they resolve your issue:
This snippet, which disables the old scrolling behavior:
elementYouWantToScroll.ontouchmove = function(e) {
e.stopPropagation();
};
Or this one, from the same:
document.ontouchmove = function(e) {
var target = e.currentTarget;
while(target) {
if(checkIfElementShouldScroll(target))
return;
target = target.parentNode;
}
e.preventDefault();
};
Then, drop in the code on Posterous:
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type="mousemove"; break;
case "touchend": type="mouseup"; break;
default: return;
}
//initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
And that should do it for you. If it doesn't, something else isn't working with Mobile Safari.
Unfortunately I haven't had the time to check out to above yet but was working on an identical problem and found that the nesting of elements in the DOM and which relation you apply it to affects the handler a lot (guess the above solves that, too - 'var target = e.currentTarget').
I used a slightly different approach (I'd love feedback on) by basically using a class "locked" that I assign to every element which (including all its children) i don't want the site to scroll when someone touchmoves on it.
E.g. in HTML:
<header class="locked">...</header>
<div id="content">...</div>
<footer class="locked"></div>
Then I have an event-listener running on that class (excuse my lazy jquery-selector):
$('.ubq_locked').on('touchmove', function(e) {
e.preventDefault();
});
This works pretty well for me on iOs and Android and at least gives me the control to not attach the listener to an element which I know causes problems. You do need to watch your z-index values by the way.
Plus I only attach the listener if it is a touch-device, e.g. like this:
function has_touch() {
var isTouchPad = (/hp-tablet/gi).test(navigator.appVersion);
return 'ontouchstart' in window && !isTouchPad;
}
This way non-touch devices will not be affected.
If you don't want to spam your HTML you could of course just write the selectors into an array and run through those ontouchmove, but I would expect that to be more costly in terms of performance (my knowledge there is limited though). Hope this can help.

Using Eclipse TableViewer, how do I navigate and edit cells with arrow keys?

I am using a TableViewer with a content provider, label provider, a ICellModifier and TextCellEditors for each column.
How can I add arrow key navigation and cell editing when the user selects the cell? I would like this to be as natural a behavior as possible.
After looking at some of the online examples, there seems to be an old way (with a TableCursor) and a new way (TableCursor does not mix with CellEditors??).
Currently, my TableViewer without a cursor will scroll in the first column only. The underlying SWT table is showing cursor as null.
Is there a good example of TableViewer using CellEditors and cell navigation via keyboard?
Thanks!
I don't know if there is a good example. I use a cluster of custom code to get what I would consider to be basic table behaviors for my application working on top of TableViewer. (Note that we are still targetting 3.2.2 at this point, so maybe things have gotten better or have otherwise changed.) Some highlights:
I do setCellEditors() on my TableViewer.
On each CellEditor's control, I establish what I consider to be an appropriate TraverseListener. For example, for text cells:
cellEditor = new TextCellEditor(table, SWT.SINGLE | getAlignment());
cellEditor.getControl().addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
switch (e.detail) {
case SWT.TRAVERSE_TAB_NEXT:
// edit next column
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
break;
case SWT.TRAVERSE_TAB_PREVIOUS:
// edit previous column
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
break;
case SWT.TRAVERSE_ARROW_NEXT:
// Differentiate arrow right from down (they both produce the same traversal #*$&#%^)
if (e.keyCode == SWT.ARROW_DOWN) {
// edit same column next row
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
}
break;
case SWT.TRAVERSE_ARROW_PREVIOUS:
// Differentiate arrow left from up (they both produce the same traversal #*$&#%^)
if (e.keyCode == SWT.ARROW_UP) {
// edit same column previous row
e.doit = true;
e.detail = SWT.TRAVERSE_NONE;
}
break;
}
}
});
(For drop-down table cells, I catch left and right arrow instead of up and down.)
I also add a TraverseListener to the TableViewer's control whose job it is to begin cell editing if someone hits "return" while an entire row is selected.
// This really just gets the traverse events for the TABLE itself. If there is an active cell editor, this doesn't see anything.
tableViewer.getControl().addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_RETURN) {
// edit first column of selected row
}
}
});
Now, how exactly I control the editing is another story. In my case, my whole TableViewer (and a representation of each column therein) is loosely wrapped up in a custom object with methods to do what the comments above say. The implementations of those methods ultimately end up calling tableViewer.editElement() and then checking tableViewer.isCellEditorActive() to see if the cell was actually editable (so we can skip to the next editable one if not).
I also found it useful to be able to programmatically "relinquish editing" (e.g. when tabbing out of the last cell in a row). Unfortunately the only way I could come up with to do that is a terrible hack determined to work with my particular version by spelunking through the source for things that would produce the desired "side effects":
private void relinquishEditing() {
// OMG this is the only way I could find to relinquish editing without aborting.
tableViewer.refresh("some element you don't have", false);
}
Sorry I can't give a more complete chunk of code, but really, I'd have to release a whole mini-project of stuff, and I'm not prepared to do that now. Hopefully this is enough of a "jumpstart" to get you going.
Here is what has worked for me:
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(tableViewer,new FocusCellOwnerDrawHighlighter(tableViewer));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(tableViewer) {
protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
I can navigate in all directions with tab while editing, and arrow around when not in edit mode.
I got it working based on this JFace Snippet, but I had to copy a couple of related classes also:
org.eclipse.jface.snippets.viewers.TableCursor
org.eclipse.jface.snippets.viewers.CursorCellHighlighter
org.eclipse.jface.snippets.viewers.AbstractCellCursor
and I don't remember exactly where I found them. The is also a org.eclipse.swt.custom.TableCursor, but I couldn't get that to work.
Have a look at
Example of enabling Editor Activation on a Double Click.
The stuff between lines [ 110 - 128 ] add a ColumnViewerEditorActivationStrategy and TableViewerEditor. In my case the I wanted a single click to begin editing so i changed line 115 from:
ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
to ColumnViewerEditorActivationEvent.MOUSE_CLICK_SELECTION. After adding this to my TableViewer, the tab key would go from field to field with the editor enabled.