Way to make a Windowless WPF window draggable without getting InvalidOperationException

后端 未结 4 1895
囚心锁ツ
囚心锁ツ 2020-12-30 10:39

I have a borderless WPF main window. I\'m trying to make it so that the end user can drag the window.

I\'ve added the following to the Window\'s constructor:

<
4条回答
  •  滥情空心
    2020-12-30 11:32

    The 'correct' way to make a borderless window movable is to return HTCAPTION in the WM_NCHITTEST message. The following code shows how to do that. Note that you will want to return HTCLIENT if the cursor is over certain of your Window's visual elements, so this code is just to get you started.

    http://msdn.microsoft.com/en-us/library/ms645618(VS.85).aspx

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    
        protected override void OnSourceInitialized(EventArgs e)
        {
            HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(this);
            hwndSource.AddHook(WndProcHook); 
            base.OnSourceInitialized(e);
        }
    
        private static IntPtr WndProcHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)
        {
            if (msg == 0x0084) // WM_NCHITTEST
            {
                handeled = true;
                return (IntPtr)2; // HTCAPTION
            }
            return IntPtr.Zero;
        }
    }
    

提交回复
热议问题