我正在编写一个锁定到另一个应用程序的应用程序,我没有源代码,但有一些东西使它显示.NET Framework异常消息。
我可以用我的代码检测它何时打开,我想得到它的句柄并关闭它。有时这个子窗口从主窗口获取标题,所以我不能依赖它来找到它的句柄。
有问题的子窗口的图像:
答案 0 :(得分:1)
好的,我解决了。事实证明,GetForegroundWindow()返回了正确的句柄,但是,因为有时异常窗口从我被绊倒的父级获取标题。
解决方法是等待使用EnumWindows更改窗口数,然后获取前景窗口的句柄并关闭它。
new Thread(() =>
{
int pid = Program.GetHelperProcess().Id;
int lastCount = -1;
while (true)
{
int newCount = WinUtil.GetWindowCount(pid);
if (lastCount != -1 && lastCount != newCount)
{
break;
}
lastCount = newCount;
Thread.Sleep(30);
}
WinUtil.CloseWindow(WinUtil.GetForegroundWindow());
}).Start();
<强> WinUtil.cs 强>
class WinUtil
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
private delegate bool EnumWindowsProc(IntPtr hWnd, int lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetShellWindow();
public static int GetWindowCount(int processId)
{
IntPtr hShellWindow = GetShellWindow();
int count = 0;
EnumWindows(delegate (IntPtr hWnd, int lParam)
{
if (hWnd == hShellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int length = GetWindowTextLength(hWnd);
if (length == 0) return true;
uint windowPid;
GetWindowThreadProcessId(hWnd, out windowPid);
if (windowPid != processId) return true;
count++;
return true;
}, 0);
return count;
}
public static string GetWindowTitle(IntPtr hWnd)
{
int textLength = GetWindowTextLength(hWnd);
StringBuilder outText = new StringBuilder(textLength + 1);
int a = GetWindowText(hWnd, outText, outText.Capacity);
return outText.ToString();
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
private const UInt32 WM_CLOSE = 0x0010;
public static void CloseWindow(IntPtr hwnd)
{
SendMessage(hwnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}