【发布时间】:2014-08-29 15:09:40
【问题描述】:
我需要检查用户当前选择了哪个窗口,如果他们选择了特定的程序,我需要做一些事情。
我之前没有使用过GetForegroundWindow函数,也找不到任何关于如何以这种方式使用它的信息。
我只需要一个 if 来比较当前窗口,看看它是否是一个特定的程序。但是,GetForegroundWindow 函数似乎并没有返回字符串或 int。所以主要是我不知道如何找出我想与之比较的程序窗口的值。
我目前有获取当前窗口的代码:
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
IntPtr selectedWindow = GetForegroundWindow();
我需要能够按如下理想方式应用它:
If (selectedWindow!="SpecificProgram")
{
<Do this stuff>
}
我希望 GetForegroundWindow 值/对象对于每个程序都是唯一的,并且不会以某种方式起作用,因为每个特定程序/窗口每次都有不同的值。
虽然我怀疑它是否重要,但我也将其作为 Windows 窗体的一部分来执行。
-感谢您的帮助
编辑:这种方式有效,并且使用当前窗口的磁贴,这使得它非常适合轻松检查窗口是否正确:
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
然后我就可以这样做了:
if (GetActiveWindowTitle()=="Name of Window")
{
DoStuff.jpg
}
【问题讨论】:
-
然后您可以平台调用
GetWindowThreadProcessId从 GetForegroundWindow 的 IntPtr 获取进程 ID。获得进程 ID 后,您可以使用 Process 类对其进行检查。 -
@Aybe 这只是获取所有窗口的列表,不是吗,我只需要获取当前选定的窗口。除非我遗漏了什么,因为简单地执行“if(process.MainWindowTitle=="Program X")”会很棒。
-
与@vcsjones 提示一起使用。
-
您知道要查找的窗口的标题吗?
标签: c# winforms if-statement dllimport