简体   繁体   English

如何使用C#捕获窗口焦点更改事件

[英]How can I capture window focus change event with c#

I want to build an application to monitor all running windows focus change event. 我想构建一个应用程序来监视所有正在运行的Windows焦点更改事件。 I know WM_KILLFOCUS (0x0008) and WM_SETFOCUS(0x0007) and when window lost focus or get focus, the message will be sent. 我知道WM_KILLFOCUS(0x0008)和WM_SETFOCUS(0x0007),当窗口失去焦点或获得焦点时,将发送该消息。 with help of spy++, I get output like this: 在spy ++的帮助下,我得到如下输出:

<00001> 0005069A S WM_SETFOCUS hwndLoseFocus:(null) <00001> 0005069A S WM_SETFOCUS hwndLoseFocus :(空)

<00002> 0005069A R WM_SETFOCUS <00002> 0005069A R WM_SETFOCUS

<00003> 0005069A S WM_KILLFOCUS hwndGetFocus:(null) <00003> 0005069A S WM_KILLFOCUS hwndGetFocus :(空)

<00004> 0005069A R WM_KILLFOCUS <00004> 0005069A R WM_KILLFOCUS

<00005> 00010096 S WM_SETFOCUS hwndLoseFocus:(null) <00005> 00010096 S WM_SETFOCUS hwndLoseFocus :(空)

<00006> 00010096 R WM_SETFOCUS <00006> 00010096 R WM_SETFOCUS

I tried to write following c# code to make it work in my winfrom application: 我试图编写以下c#代码以使其在我的winfrom应用程序中工作:

[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
 public IntPtr handle;
 public uint msg;
 public IntPtr wParam;
 public IntPtr lParam;
 public uint time;
 public System.Drawing.Point p;
}
[DllImport("user32.dll")]
public static extern sbyte GetMessage(out NativeMessage lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);

NativeMessage msg = new NativeMessage();
        sbyte ret;
        while ((ret = GetMessage( out msg, IntPtr.Zero, 0, 0)) != -1)
        {
            if (ret == -1)
            {
                //-1 indicates an error
            }
            else
            {
                if (msg.msg == 0x0008 || msg.msg == 0x0007)
                {
                    this.textBox1.Text = "ret is: " + ret;
                }
            }
        }

Unfortunately, I never get message WM_KILLFOCUS and WM_SETFOCUS. 不幸的是,我从未收到消息WM_KILLFOCUS和WM_SETFOCUS。

I actually want to trigger an event in my application when I find the get/lost focus event happens in all running windows. 当我发现get / lost focus事件发生在所有运行的窗口中时,我实际上想在应用程序中触发一个事件。 How can I make it work? 我该如何运作?

Thanks. 谢谢。

使用Form.ActivedForm.Deactivate事件来查找表单是丢失还是获得焦点。

如果您真的想进入本机窗口消息的令人讨厌的世界,则应使用WndProc

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

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