[英]How to check if my application is the Windows activate form
I've created some global Hot keys for my application and I want them to work only if my application is active. 我已经为我的应用程序创建了一些全局热键,并且我希望它们仅在我的应用程序处于活动状态时才起作用。 (It should not work if my application is not the active form).
(如果我的应用程序不是活动表单,则它不起作用)。
So how can I check if my C#
winform application is the active form among all the other windows applications? 那么,如何检查我的
C#
winform应用程序是否是所有其他Windows应用程序中的活动窗体?
I tried 我试过了
if(this.Focused)
//Do somthing
But it's not working 但这没用
Try this: 尝试这个:
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
public static bool Activates()
{
var x = GetForegroundWindow();
if (x == IntPtr.Zero) {
return false;
}
var y = Process.GetCurrentProcess().Id;
int i;
GetWindowThreadProcessId(x, out i);
return i == y;
}
You can also refer: C#: Detecting which application has focus 您还可以参考: C#:检测哪个应用程序具有焦点
You can use Windows API function GetForegroundWindow
and GetWindowText
. 您可以使用Windows API函数
GetForegroundWindow
和GetWindowText
。
GetForegroundWindow : GetForegroundWindow :
The GetForegroundWindow function returns a handle to the window with which the user is currently working. GetForegroundWindow函数返回用户当前正在使用的窗口的句柄。
GetWindowText : GetWindowText :
The GetWindowText function copies the text of the specified window's title bar (if it has one) into a buffer. GetWindowText函数将指定窗口的标题栏(如果有的话)的文本复制到缓冲区中。
Add below code to declare API functions : 添加以下代码以声明API函数:
[ DllImport("user32.dll") ]
static extern int GetForegroundWindow();
[ DllImport("user32.dll") ]
static extern int GetWindowText(int hWnd, StringBuilder text, int count);
Start a timer : 启动计时器:
private void timer1_Tick(object sender, System.EventArgs e)
{
GetActiveWindow();
}
Active window function : 活动窗口功能:
private void GetActiveWindow()
{
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if ( GetWindowText(handle, Buff, nChars) > 0 )
{
this.captionWindowLabel.Text = Buff.ToString();
this.IDWindowLabel.Text = handle.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.