点击可拖动按钮的事件?

时间:2017-11-09 14:19:27

标签: c# winforms

所以,我制作了一个可以拖动这些事件的按钮:

bool isMouseClicked;
    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            isMouseClicked = true;
        }
    }

    private void button1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMouseClicked == true)
            //You then set your location of your control. See below:
            button1.Location = new Point(MousePosition.X, MousePosition.Y);
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        isMouseClicked = false;
    }

现在,我想在“Click”事件中插入一些内容。当我尝试拖动按钮时,将执行“Click”事件中的操作。我只想在拖动按钮时移动按钮,并在单击它时从“Click”事件执行操作。我怎么能这样做?

1 个答案:

答案 0 :(得分:-1)

我建议您将bool命名为isMouseDown。现在,在同一控件上发生MouseDown和MouseUp事件时会触发Click事件。因此,添加另一个bool justDragged,在MouseDown上将其设置为false,在MouseMove和isMouseDown上将其设置为true,并在Click事件中对其进行测试。

顺便说一下,这个信息是关于SO的,只是有点散乱。

bool isMouseDown = false;
bool justDragged = false;

private void button1_MouseDown(object sender, MouseEventArgs e) {
    if (e.Button == MouseButtons.Left) {
        isMouseDown = true;
        justDragged = false;
    }
}

private void button1_MouseMove(object sender, MouseEventArgs e) {
    if (isMouseDown) {
        //You then set your location of your control. See below:
        button1.Location = new Point(MousePosition.X, MousePosition.Y);
        justDragged = true;
    }
}

private void button1_MouseUp(object sender, MouseEventArgs e) {
    isMouseDown = false;
}

private void button1_Click(object sender, MouseEventArgs e) {
    if (!justDragged) { // then we clicked
        // do click handling
    }
}