这个问题与这个问题 ( Detect active window changed using C# without polling ) 非常相似,并且该接受答案上的代码在 Windows 窗体应用程序中工作得很好,但在控制台应用程序中却不行。
如何在不使用控制台应用程序进行无限迭代(或任何类型的轮询)的情况下检测事件窗口已更改?
提前致谢。
最佳答案
只需进行一些更改即可将其更改为作为控制台应用程序运行。这是一个工作代码。
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
dele = new WinEventDelegate(WinEventProc);
IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
Application.Run(); //<----
}
static WinEventDelegate dele = null; //STATIC
delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
private const uint WINEVENT_OUTOFCONTEXT = 0;
private const uint EVENT_SYSTEM_FOREGROUND = 3;
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private static string GetActiveWindowTitle() //STATIC
{
const int nChars = 256;
IntPtr handle = IntPtr.Zero;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
public static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) //STATIC
{
Console.WriteLine(GetActiveWindowTitle());
}
}
}
关于c# - 使用 C# 和控制台应用程序检测事件窗口的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32015004/