单击表单时移动表单,而不是顶部栏区域

时间:2014-02-19 01:52:52

标签: c# winforms mousemove

我正在制作一个没有控制盒的程序,因为我不想要一个。我试图这样做,当我点击任何不是控件的区域时,它会移动。这是我到目前为止的代码:

    public Form1()
    {
        InitializeComponent();
        BackColor = Color.linen;
        TransparencyKey = Color.Linen;
    }
    bool canMove = false;
    int mouseX;
    int mouseY;
    public void MoveForm()
    {
        mouseX = MousePosition.X - Form1.ActiveForm.Location.X;
        mouseY = MousePosition.Y - Form1.ActiveForm.Location.Y;
        Form1.ActiveForm.Location = new Point(mouseX, mouseY);
    }

    private void Form1_MouseDown(object sender, MouseEventArgs e)
    {
        canMove = true;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (canMove)
            MoveForm();

    }

    private void Form1_MouseUp(object sender, MouseEventArgs e)
    {
        canMove = false;
    }

适用于移动,但如果表单处于边缘,它将无法正确显示。 它做的另一件事是,当它被拖动时闪烁。

有什么方法可以正确地做到这一点吗?

2 个答案:

答案 0 :(得分:2)

只需将此代码添加到表单即可:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private const int HTCLIENT = 0x0001;
    private const int HTCAPTION = 0x0002;
    private const int WM_NCHITTEST = 0x0084;

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if ((m.Msg == WM_NCHITTEST) & (m.Result.ToInt32() == HTCLIENT))
        {
            m.Result = (IntPtr)HTCAPTION;
        }
    }

}

答案 1 :(得分:0)

代码在vb中(抱歉):

Private posx, posy As Integer

Private Sub Form1_MouseDown(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown
    canMove = 1

    posx = MousePosition.X
    posy = MousePosition.Y
End Sub

Private Sub Form1_MouseMove(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
    If canMove = 1 And (posx <> MousePosition.X Or posy <> MousePosition.Y) Then
        MoveForm()
    End If

    posx = MousePosition.X
    posy = MousePosition.Y
End Sub

它确实来回(因为你在MoveForm()中的代码),但如果你不移动鼠标就会停止。

编辑:在c#(使用过的翻译)

int posx, posy;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    canMove = true;
    posx = MousePosition.X;
    posy = MousePosition.Y;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (canMove == 1 && (posx != MousePosition.X || posy != MousePosition.Y)) {
        MoveForm();
    }

    posx = MousePosition.X;
    posy = MousePosition.Y;
}

瓦尔特