且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取.NET应用程序的活动窗口

更新时间:2023-11-22 21:57:46

如果我理解正确的问题,你可以使用Win32 API的 GetActiveWindow 这一点。这应该在两个窗体和WPF应用程序。

If I understand the question correctly, you can use the Win32 API GetActiveWindow for this. This should work in both Forms and WPF apps.

[DllImport("user32.dll")]
static extern IntPtr GetActiveWindow();

[DllImport("user32.dll")]
public static extern int SendMessage(int hWnd, IntPtr msg, int wParam, int lParam);

public const int WM_SYSCOMMAND = 0x0112;
public const int SC_CLOSE = 0xF060;

// close the active window using API        
private void FindAndCloseActiveWindow()
{
 IntPtr handle=GetActiveWindow();
 SendMessage(handle, WM_SYSCOMMAND, SC_CLOSE, 0);
}