用户更改活动进程时的Fire事件

str*_*103 4 c# winforms

是否存在当程序用户将活动窗口更改为其他进程的事件时触发的事件或创建事件的方法?

如果没有这样的事件,做出类似事情的最佳方法是什么?

我目前有一个每3秒运行一次Process.GetCurrentProcess()的计时器,但我正在寻找更好,更有效的方法,我不想降低间隔,因为有制作程序的风险占用太多资源或者需要花费太多时间来不断检查活动过程.

我知道有很多Windows内置的功能基本上是隐藏的,我没有足够的知识可以知道,所以如果有人对这样的事情有任何想法,那么如果你可以帮助我的话会很棒.

Jam*_*mes 5

SetWinEventHook API不正是你所期待的在这里.您需要做的就是在应用程序启动时使用正确的选项调用此选项,并且只要用户从桌面上当前运行的任何进程更改焦点,您就应该开始接收通知.

[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, int idProcess, int idThread, uint dwflags);
[DllImport("user32.dll")]
internal static extern int UnhookWinEvent(IntPtr hWinEventHook);
internal delegate void WinEventProc(IntPtr hWinEventHook, uint iEvent, IntPtr hWnd, int      idObject, int idChild, int dwEventThread, int dwmsEventTime);

const uint WINEVENT_OUTOFCONTEXT = 0;
const uint EVENT_SYSTEM_FOREGROUND = 3;
private IntPtr winHook;
private WinEventProc listener;

public void StartListeningForWindowChanges()
{
    listener = new WinEventProc(EventCallback);
    //setting the window hook
    winHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, listener, 0, 0, WINEVENT_OUTOFCONTEXT);
}

public void StopListeningForWindowChanges()
{
    UnhookWinEvent(winHook);
}

private static void EventCallback(IntPtr hWinEventHook, uint iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime)
{
    // handle active window changed!
}
Run Code Online (Sandbox Code Playgroud)