我需要检查用户当前选择了哪个窗口,并在他们选择了特定程序时做一些事情。
我以前没有使用过 GetForegroundWindow 函数,也找不到任何关于如何以这种方式使用它的信息。
我只需要一个 if 比较当前窗口以查看它是否是特定程序。但是,GetForegroundWindow 函数似乎没有返回字符串或整数。所以主要是我不知道如何找出我想与之比较的程序窗口的值。
我目前有获取当前窗口的代码:
[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
}
最佳答案
它有一些代码但可以工作:
#region Retrieve list of windows
[DllImport("user32")]
private static extern int GetWindowLongA(IntPtr hWnd, int index);
[DllImport("USER32.DLL")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
private const int GWL_STYLE = -16;
private const ulong WS_VISIBLE = 0x10000000L;
private const ulong WS_BORDER = 0x00800000L;
private const ulong TARGETWINDOW = WS_BORDER | WS_VISIBLE;
internal class Window
{
public string Title;
public IntPtr Handle;
public override string ToString()
{
return Title;
}
}
private List<Window> windows;
private void GetWindows()
{
windows = new List<Window>();
EnumWindows(Callback, 0);
}
private bool Callback(IntPtr hwnd, int lParam)
{
if (this.Handle != hwnd && (GetWindowLongA(hwnd, GWL_STYLE) & TARGETWINDOW) == TARGETWINDOW)
{
StringBuilder sb = new StringBuilder(100);
GetWindowText(hwnd, sb, sb.Capacity);
Window t = new Window();
t.Handle = hwnd;
t.Title = sb.ToString();
windows.Add(t);
}
return true; //continue enumeration
}
#endregion
并检查用户窗口:
IntPtr selectedWindow = GetForegroundWindow();
GetWindows();
for (i = 0; i < windows.Count; i++)
{
if(selectedWindow == windows[i].Handle && windows[i].Title == "Program Title X")
{
//Do stuff
break;
}
}
瓦尔特
关于c# - 在 if 语句中使用 GetForegroundWindow 结果来检查用户的当前窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25571134/