winforms C# -窗体的鼠标按下事件不起作用

kcwpcxri  于 2023-02-19  发布在  C#
关注(0)|答案(2)|浏览(460)

我试图使窗口窗体可拖动,但当我试图检测鼠标按下和向上事件的形式,但事件不火。其他事情似乎工作,但这两个事件没有。

public form()
{
    InitializeComponent();
    this.BackColor = Color.Fuchsia;
    this.TransparencyKey = this.BackColor;

    Debug.Write("initialized");
}

private void form_MouseDown(object sender, MouseEventArgs e)
{
    Debug.Write("dragging..");
}

private void form_MouseUp(object sender, MouseEventArgs e)
{
    Debug.Write("drag done");
}
svmlkihl

svmlkihl1#

最好添加一个panel到你的窗体并设置Docktop以便覆盖标题栏区域.然后使用这个示例代码

private bool isDragging = false;
private Point lastLocation;

private void panel_MouseDown(object sender, MouseEventArgs e)
{
    isDragging = true;
    lastLocation = e.Location;
}

private void panel_MouseMove(object sender, MouseEventArgs e)
{
    if (isDragging)
    {
        this.Location = new Point(
        (this.Location.X - lastLocation.X) + e.X, 
        (this.Location.Y - lastLocation.Y) + e.Y);

        this.Update();
    }
 }

 private void panel_MouseUp(object sender, MouseEventArgs e)
 {
    isDragging = false;
 }

别忘了在窗体构造函数中添加处理程序

panel.MouseDown += panel_MouseDown;
panel.MouseMove += panel_MouseMove;
panel.MouseUp += panel_MouseUp;
gk7wooem

gk7wooem2#

在窗体的构造函数中,注册用于侦听如下所示的鼠标按下事件的方法。

public form() { 
 InitializeComponent(); 
 this.BackColor = Color.Fuchsia; 
 this.TransparencyKey = this.BackColor; 
 Debug.Write("initialized");
 //register the methods to listen for the events
 this.MouseDown += form_MouseDown;
 this.MouseUp += form_MouseUp;
 }
 private void form_MouseDown(object sender, 
  MouseEventArgs e) { 

   Debug.Write("dragging.."); 

} 
 private void form_MouseUp(object sender, 
 MouseEventArgs e) { 

   Debug.Write("drag done");
 }

相关问题