記錄一下WPF 調用 窗口自帶的Hide() 方法,用 Win32 的ShowWindow 顯示窗口異常的問題
最近有小伙伴的應用里邊,需要跨進程的方式,顯示隱藏窗口。
在WPF 自身的應用中,使用的最多的就是 窗口自帶的 Hide()和Show() 方法
1、創建一個HideWindow的窗口,添加按鈕,在點擊按鈕的時候,調用Hide()方法。

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { this.Hide(); } }
2、創建一個激活的窗口,添加按鈕,在點擊按鈕的時候,將HideWindow的窗口激活并顯示

public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool SetActiveWindow(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true)] private static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll", SetLastError = true)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); // 窗口顯示狀態常量 private const int SW_SHOWNOACTIVATE = 4; // 顯示窗口但不激活 private const int SW_SHOWNA = 8; // 顯示窗口但不激活 private const int SW_SHOWMINIMIZED = 2; // 顯示最小化窗口 // 窗口定位常量 private const uint SWP_NOACTIVATE = 0x0010; private const uint SWP_NOZORDER = 0x0004; private const uint SWP_NOSIZE = 0x0001; private const uint SWP_NOMOVE = 0x0002; private const uint SWP_SHOWWINDOW = 0x0040; // 定義窗口狀態常量 private const int SW_RESTORE = 9; // 激活并顯示窗口。如果窗口最小化或最大化,系統將其還原到原始大小和位置。 private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var intptr = FindWindow(null, "HideWindow"); if (intptr != IntPtr.Zero) { var isVisible = IsWindowVisible(intptr); var showResult = ShowWindow(intptr, SW_RESTORE); //uint flags = SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW; //SetWindowPos(intptr, IntPtr.Zero, 0, 0, 0, 0, flags); isVisible = IsWindowVisible(intptr); var setResult = SetForegroundWindow(intptr); } } }
結果如下:
在設置ShowWindow的方法,返回的是False,并且HideWindow的窗口是黑屏的


解決方法:
1、修改HideWindow 窗口的隱藏方式:
通過調用Win32的 ShowWindow(handle, SW_Hide);
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { Win32Hide(); // this.Hide(); } private void Win32Hide() { var handle = new WindowInteropHelper(this).Handle; ShowWindow(handle, SW_Hide); } private int SW_Hide = 0; [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); }
2、ActiveWindow 的窗口的方法保持不變
結果如下:
ActiveWindow 的 窗口var showResult = ShowWindow(intptr, SW_RESTORE); 返回之為True,并且窗口可以激活并顯示


代碼Demo 鏈接 :wutangyuan/wutyDemo: Demo代碼備份

浙公網安備 33010602011771號