bob*_*bob 6 c# if-statement dllimport winforms
我需要检查用户当前选择的窗口,并且如果他们选择了特定程序则执行操作.
我之前没有使用过GetForegroundWindow函数,也找不到有关如何以这种方式使用它的任何信息.
我只需要比较当前窗口,看看它是否是一个特定的程序.但是,GetForegroundWindow函数似乎不会返回字符串或int.所以主要是我不知道如何找出我要比较的程序窗口的值.
我目前有代码来获取当前窗口:
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
IntPtr selectedWindow = GetForegroundWindow();
Run Code Online (Sandbox Code Playgroud)
我需要能够如下理想地应用它:
If (selectedWindow!="SpecificProgram")
{
<Do this stuff>
}
Run Code Online (Sandbox Code Playgroud)
我希望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;
}
Run Code Online (Sandbox Code Playgroud)
然后我可以这样做:
if (GetActiveWindowTitle()=="Name of Window")
{
DoStuff.jpg
}
Run Code Online (Sandbox Code Playgroud)
它有一些代码,但它有效:
#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
Run Code Online (Sandbox Code Playgroud)
并检查用户窗口:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
瓦尔特
归档时间: |
|
查看次数: |
16129 次 |
最近记录: |