C# 获取 .net 应用程序的活动窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12019524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 20:05:40  来源:igfitidea点击:

Get Active Window of .net application

c#.netwindows

提问by Maanu

I have an application named ProLaunch.exe. I want to get the active window in it and close it if the user is not performing any operation for the speicified period. A timer in the application will be used for this purpose.

我有一个名为 ProLaunch.exe 的应用程序。如果用户在指定时间内没有执行任何操作,我想在其中获取活动窗口并关闭它。应用程序中的计时器将用于此目的。

How can I get the active window and close it?

如何获取活动窗口并关闭它?

采纳答案by Brian

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

如果我正确理解了这个问题,您可以为此使用 Win32 API GetActiveWindow。这应该适用于 Forms 和 WPF 应用程序。

[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);
}