C# 如何监听当前操作系统活动窗口发生改变
时间: 2023-08-10 13:01:53 浏览: 96
要在 C# 中监听当前操作系统活动窗口发生改变,你可以使用 System.Windows.Forms 命名空间中的 SystemEvents 类的ForegroundWindowChanged 事件。以下是一个示例代码:
```csharp
using System;
using System.Windows.Forms;
class Program
{
static void Main()
{
// 注册 ForegroundWindowChanged 事件
SystemEvents.ForegroundWindowChanged += OnForegroundWindowChanged;
// 等待退出程序
Console.WriteLine("按任意键退出程序...");
Console.ReadKey();
}
static void OnForegroundWindowChanged(object sender, EventArgs e)
{
// 获取当前活动窗口的标题
string foregroundWindowTitle = GetForegroundWindowTitle();
// 输出当前活动窗口的标题
Console.WriteLine("当前活动窗口改变: " + foregroundWindowTitle);
}
static string GetForegroundWindowTitle()
{
IntPtr foregroundWindowHandle = NativeMethods.GetForegroundWindow();
const int MaxLength = 256;
var buffer = new char[MaxLength];
NativeMethods.GetWindowText(foregroundWindowHandle, buffer, MaxLength);
return new string(buffer);
}
}
// 使用 Windows API 获取窗口标题
class NativeMethods
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, char[] lpString, int nMaxCount);
}
```
上述代码中,我们通过注册 `SystemEvents.ForegroundWindowChanged` 事件来监听当前活动窗口发生改变的情况。每当活动窗口发生改变时,`OnForegroundWindowChanged` 方法会被调用,并获取当前活动窗口的标题,并输出到控制台。
请注意,此代码使用了 Windows API 来获取窗口标题。`GetForegroundWindow` 函数用于获取当前活动窗口的句柄,然后使用 `GetWindowText` 函数获取窗口的标题。你可以根据需要修改和扩展代码。