简体   繁体   中英

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

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM