简体   繁体   English

如何确定Windows窗体中的文本框是否具有焦点

[英]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. 假设我在Windows窗体中嵌入了Internet Explorer,然后导航到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. 您仍然没有解释WebBrowser的功能,但是问题似乎在跟踪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. 我不知道窗体级别的事件,但是您可以将事件处理程序挂钩到所有相关控件的Enter或GotFocus事件。

// 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). 我相信您想要做的是接收HTMLTextContainerEvents2 dispinterface并响应onFocus(可能还有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). 我假设您可以获取指向要跟踪的所有对象的IHTMLElement指针(通过使用getElementsByTagName或类似的东西)。 Once you have that, 一旦有了,

  1. Query the IHTMLElemnt for IConnectionPointContainer . 查询IHTMLElemnt的IConnectionPointContainer
  2. Call IConnectionPointContainer::FindConnectionPoint(DIID_DHTMLTextContainerEvents2) 调用IConnectionPointContainer :: FindConnectionPoint(DIID_DHTMLTextContainerEvents2)
  3. Call IConnectionPoint::Advise() on the IConnectionPoint obtained in step 2. 在步骤2中获得的IConnectionPoint上调用IConnectionPoint :: Advise()。
  4. And of course you need to implement IDispatch::Invoke() which will be your callback. 当然,您需要实现IDispatch :: Invoke(),它将作为您的回调。
  5. Handle DISPID_HTMLELEMENTEVENTS2_ONFOCUS, etc. 处理DISPID_HTMLELEMENTEVENTS2_ONFOCUS等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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