.net 当拖动我的C#表单时,它会传送到左上角

t5fffqht  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(101)

当我在最大化模式下从我的c#表单中拖动自定义导航栏时,我将WindowState设置为normal,表单传送到左上角,这是我当前的拖动代码:

private void TopBarNav_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDragging = true;
        offset = e.Location;
    }
}
private void TopBarNav_MouseMove(object sender, MouseEventArgs e)
{
    if (isDragging)
    {
        this.WindowState = FormWindowState.Normal;
        ExpandButton.IconChar = IconChar.Expand;
        Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
        Point newLocation = new Point(
        Cursor.Position.X - offset.X,
        Cursor.Position.Y - offset.Y
    );

    this.Location = newLocation;
    }
}

private void TopBarNav_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDragging = false;
    }
}

字符串
before dragging
After dragging
我尝试了很多方法,包括将表单传送到光标上,但这对用户体验并不好

zkure5ic

zkure5ic1#

您需要将窗体的Location属性设置为新位置,而不是设置Cursor.Position.X和Cursor.Position.Y属性。这将防止窗体在WindowState设置为Normal时传送到左上角。
更新后的代码应该如下所示:

private void TopBarNav_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDragging = true;
        offset = e.Location;
    }
}
private void TopBarNav_MouseMove(object sender, MouseEventArgs e)
{
    if (isDragging)
    {
        this.WindowState = FormWindowState.Normal;
        ExpandButton.IconChar = IconChar.Expand;
        Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
        Point newLocation = new Point(
        this.Location.X + e.X - offset.X,
        this.Location.Y + e.Y - offset.Y
    );

    this.Location = newLocation;
    }
}

private void TopBarNav_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        isDragging = false;
    }
}

字符串

相关问题