Beaker
Beaker

Reputation: 2894

How to determine if a textbox in a windows form has focus

Let's say I have internet explorer embedded in a windows form and I then navigate to a random page on the web. How can I determine when a textbox (or any other control that can accept text input for that matter) becomes the item in focus? Basically, every time the mouse is clicked I can check to see if the item in focus is a textbox or some other control for text input and then act appropriately.

Thanks in advance,

Bob

Upvotes: 0

Views: 2614

Answers (2)

i_am_jorf
i_am_jorf

Reputation: 54640

I believe what you want to do is sink the HTMLTextContainerEvents2 dispinterface and respond to onFocus (and potentially onBlur).

You're right that you'll have to do the interop via pinvoke yourself. I assume you can get IHTMLElement pointers to all of the objects you want to track (by using getElementsByTagName or some such thing). Once you have that,

  1. Query the IHTMLElemnt for IConnectionPointContainer.
  2. Call IConnectionPointContainer::FindConnectionPoint(DIID_DHTMLTextContainerEvents2)
  3. Call IConnectionPoint::Advise() on the IConnectionPoint obtained in step 2.
  4. And of course you need to implement IDispatch::Invoke() which will be your callback.
  5. Handle DISPID_HTMLELEMENTEVENTS2_ONFOCUS, etc.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273784

You still haven't explained the roll of the WebBrowser but the problem seems to be tracking the Input Focus. I don't know of a Form level event but you can hook an eventhandler to the Enter or GotFocus event of all relevant Controls.

// in Form_Load
foreach (var control in this.Controls)  control.Enter += OnEnterControl;


private void OnEnterControl(object sender, EventArgs e)
{
  focusControl = (sender as Control);
}

Upvotes: 1

Related Questions