[英]C# Close child window from another process
我正在編寫一個可以鎖定到另一個應用程序的應用程序,我沒有該應用程序的源代碼,但是有某些事情可以使它顯示.NET Framework異常消息。
我可以用我的代碼檢測它何時打開,並且我想獲取它的句柄並關閉它。 有時,此子窗口從主窗口獲取標題,因此我不能依靠它來找到其句柄。
相關子窗口的圖片:
好的,我解決了。 事實證明,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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.