简体   繁体   English

通过控件和MouseEventArgs拖放表单

[英]Drag/Drop Form via control and MouseEventArgs

I am currently using the code mentioned to move my form when clicking and moving the mouse on a specific control(in this case toolStrip). 我正在使用上面提到的代码在单击并在特定控件上移动鼠标时移动我的表单(在本例中为toolStrip)。

private void toolStrip1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left) //Wenn die linke Maustaste gedrückt wurde,
            FormMouseDownLocation = e.Location; //wird die Position der Maus gespeichert
    }

    private void toolStrip1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left) //Wird die Linke taste gedrückt und bewegt,
        {
            this.Left += e.X - FormMouseDownLocation.X; //so verschiebt sich das Fenster bei jeder Bewegung um die Positionänderung der Maus (hier die X Pos)

            this.Top += e.Y - FormMouseDownLocation.Y; //so verschiebt sich das Fenster bei jeder Bewegung um die Positionänderung der Maus (hier die Y Pos)
        }
    }

Now I have a problem. 现在我有一个问题。 The cursor is moving faster than the form, so often the cursor leaves the toolStrip and the form stops moving. 光标移动得比窗体快,因此光标经常离开toolStrip并且窗体停止移动。 This only happens, when I use this code combined with a control other than the mainform. 只有在我将此代码与主窗体以外的控件结合使用时才会发生这种情况。

Is there any solution to this behaviour or maybe a better way to change the position of a form when clicking on another control? 有没有解决这种行为的方法,或者是在点击另一个控件时更改表单位置的更好方法?

Thanks in advance 提前致谢

Additional info: I am using winforms, FormBorderStyle: None 附加信息:我正在使用winforms,FormBorderStyle:无

This is a common problem, you have to capture the mouse to ensure you are still getting MouseMove events when the cursor moves outside of the toolstrip window. 这是一个常见问题,您必须捕获鼠标以确保在光标移动到工具条窗口之外时仍然获得MouseMove事件。 An issue with any window but more likely with a toolstrip because they tend to be slender. 任何窗口的问题,但更可能使用工具条,因为它们往往是苗条的。 Fix: 固定:

private void toolStrip1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) {
        FormMouseDownLocation = e.Location;
        toolStrip1.Capture = true;
    }
}

private void toolStrip1_MouseUp(object sender, MouseEventArgs e)
{
    toolStrip1.Capture = false;
}

Please do pick better variable names. 请选择更好的变量名称。 "FormMouseDownLocation" is extraordinarily inaccurate, the location is completely unrelated to the form. “FormMouseDownLocation”非常不准确,该位置与表单完全无关。

You can refer to this . 你可以参考这个 You can use a panel or even any object that you can use as header for example. 例如,您可以使用面板甚至任何可用作标题的对象。 Please check on the link. 请检查链接。 Not the part where they use WndProc 不是他们使用WndProc的部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM