在 C# 中从图片框中移动窗口窗体

本文关键字:移动 窗口 窗体 | 更新日期: 2023-09-27 17:56:24

我有一个没有任何边框的窗口表单。所以我添加了一个图片框,我希望在单击该图片框时移动整个表单。

    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HT_CAPTION = 0x2;
    [DllImportAttribute("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd,
    int Msg, int wParam, int lParam);
    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();
    private void header_image_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        } 
    }

这就是我正在使用的 atm 的代码。但我的问题是,如果我移动光标的速度非常快,它就不会粘在图片框上。

我试图找到解决方案,但没有任何结果。我使用了这两个链接中的一些信息:

链接 1

链接 2

有什么想法吗?

编辑:这是我表单的整个代码

    public Form1()
    {
        InitializeComponent();
    }
    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HT_CAPTION = 0x2;
    [DllImportAttribute("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd,
    int Msg, int wParam, int lParam);
    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();
    private void header_image_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        } 
    }

在 C# 中从图片框中移动窗口窗体

参考以下代码:

 private bool draging = false;
        private Point pointClicked;
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (draging)
            {
                Point pointMoveTo;
                pointMoveTo = this.PointToScreen(new Point(e.X, e.Y));
                pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y);
                this.Location = pointMoveTo;
            }
        }
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                draging = true;
                pointClicked = new Point(e.X, e.Y);
            }
            else
            {
                draging = false;
            }
        }
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            draging = false;
        }

使用 MouseMove() 事件而不是 MouseDown()

    private void header_image_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            ReleaseCapture();
            SendMessage(this.Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
        }
    }