Loading a WPF Window without showing it

前端 未结 12 825
独厮守ぢ
独厮守ぢ 2020-12-12 16:14

I create a global hot key to show a window by PInvoking RegisterHotKey(). But to do this I need that window\'s HWND, which doesn\'t exist until the

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 16:51

    You can also change the window into a so called message-only window. As this window type does not support graphical elements it will never be shown. Basically it comes down to calling:

        SetParent(hwnd, (IntPtr)HWND_MESSAGE);
    

    Either create a dedicated message window which will always be hidden, or use the real GUI window and change it back to a normal window when you want to display it. See the code below for a more complete example.

        [DllImport("user32.dll")]
        static extern IntPtr SetParent(IntPtr hwnd, IntPtr hwndNewParent);
    
        private const int HWND_MESSAGE = -3;
    
        private IntPtr hwnd;
        private IntPtr oldParent;
    
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
    
            if (hwndSource != null)
            {
                hwnd = hwndSource.Handle;
                oldParent = SetParent(hwnd, (IntPtr)HWND_MESSAGE);
                Visibility = Visibility.Hidden;
            }
        }
    
        private void OpenWindowMenuItem_Click(object sender, RoutedEventArgs e)
        {
            SetParent(hwnd, oldParent);
            Show();
            Activate();
        }
    

    For me the solution of setting the width, height to zero and style to none didn't work out, as it still showed a tiny window, with an annoying shadow of what seems to be the border around a 0x0 window (tested on Windows 7). Therefore I'm providing this alternative option.

提交回复
热议问题