在不获取 InvalidOperationException 的情况下使无窗口 WPF 窗口可拖动的方法 [英] Way to make a Windowless WPF window draggable without getting InvalidOperationException

查看:17
本文介绍了在不获取 InvalidOperationException 的情况下使无窗口 WPF 窗口可拖动的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无边框 WPF 主窗口.我正在努力使最终用户可以拖动窗口.

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

我已将以下内容添加到 Window 的构造函数中:

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

this.MouseLeftButtonDown += delegate { DragMove(); };

问题是,我有一个带有两个按钮的对话框.当我单击这些按钮之一时,我收到一个未处理的 InvalidOperationException 消息只能在鼠标主按钮按下时调用 DragMove."

The problem is, I have a dialog box that opens up with two buttons. When I click one of these buttons, I get an InvalidOperationException unhandled with the message "Can only call DragMove when the primary mouse button is down."

这带来了几个问题:为什么对话框中的 mousedown 事件与此有关?如果没有这个例外,我怎么能做到这一点?

This poses a few questions: Why would a mousedown event in a dialog have anything to do with this? How can I do this without this exception?

谢谢!

推荐答案

使无边框窗口可移动的正确"方法是在 WM_NCHITTEST 消息中返回 HTCAPTION.下面的代码展示了如何做到这一点.请注意,如果光标位于 Window 的某些视觉元素上,您将希望返回 HTCLIENT,因此此代码只是为了让您入门.

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;
    }
}

这篇关于在不获取 InvalidOperationException 的情况下使无窗口 WPF 窗口可拖动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆