2012-05-02 54 views
3

寻找在具有定时器,鼠标​​,鼠标按下,鼠标松开事件不是一起工作

对不起,如果这个问题已经被问,我找不到任何类似的问题即时通讯一些帮助。

的想法是当点击一个图片被改变的图像为ON。

如果图片框保持超过2秒,打开一个新的形式和离开的PictureBox为OFF。

但是,如果图片框上点击,然后保持2秒,然后返回我需要的PictureBox的状态留在。

这是我到目前为止尝试过的。

我相信这才能正常工作,我需要从存在的停止MouseUp事件。

有没有一种方法,当出现蜱我可以停止的MouseUp?

有没有更容易/更好的方法来做到这一点?

任何帮助,将不胜感激。

private void time_HoldDownInternal_Tick(object sender, EventArgs e) 
    { 
     time_HoldDownInternal.Enabled = false; 
     time_HoldDownInternal.Interval = 1000; 
     form1show.Visible = true; 
    } 

    private void pb_pictureBoxTest_MouseDown(object sender, MouseEventArgs e) 
    { 
     mainMenuVariables.mousedown = true; 
     time_HoldDownInternal.Enabled = true; 
    } 

    private void pb_pictureBoxTest_MouseUp(object sender, MouseEventArgs e) 
    { 
     mainMenuVariables.mousedown = false; 
     //MessageBox.Show("mouse up"); 
     time_HoldDownInternal.Enabled = false; 
     time_HoldDownInternal.Interval = 1000; 
    } 

    private void pb_pictureBoxTest_Click(object sender, EventArgs e) 
    { 
     if (mainMenuVariables.mousedown == true) 
     { 
      if (mainMenuVariables.pictureBox == false) 
      { 
       mainMenuVariables.pictureBox = true; 
       pb_pictureBoxTest.Image = new Bitmap(mainMenuVariables.pictureBoxOn); 
       return; 
      } 
      if (mainMenuVariables.pictureBox == true) 
      { 
       mainMenuVariables.pictureBox = false; 
       pb_pictureBoxTest.Image = new Bitmap(mainMenuVariables.pictureBoxOff); 
       return; 
      } 
     } 
     if (mainMenuVariables.mousedown == false) 
     { 
      //nothing 
     } 
    } 

回答

5

而不是启动一个计时器,只是记录下鼠标的当前时间。然后在鼠标上,检查它是否已经2秒。例如:

private void pb_pictureBoxTest_MouseDown(object sender, MouseEventArgs e) 
{ 
    mainMenuVariables.mousedown = true; 
    mainMenuVariables.mousedowntime = DateTime.Now; 
} 

private void pb_pictureBoxTest_MouseUp(object sender, MouseEventArgs e) 
{ 
    mainMenuVariables.mousedown = false; 
    var clickDuration = DateTime.Now - mainMenuVariables.mousedowntime; 

    if (clickDuration > TimeSpan.FromSeconds(2)) 
    { 
     // Do 'hold' logic (e.g. open dialog, etc) 
    } 
    else 
    { 
     // Do normal click logic (e.g. toggle 'On'/'Off' image) 
    } 
} 
+0

我会看看现在这样做,但如果已经打开或关闭,如何更改图像打开/关闭? – justin89

+0

@ justin89查看我上面的编辑 - 根据您的代码添加了一个代码示例。 – Tyson

+0

效果很好,我想改变的唯一的事情就是现在打开你的表格之后。我想使窗体出现一个按钮已被保持2秒 即时通讯寻找添加您的代码到mousedown以及但它似乎并没有工作。再次感谢你的帮助。 [代码] 变种clickDuration = DateTime.Now - mainMenuVariables.mousedowntime; 如果(clickDuration> TimeSpan.FromSeconds(2)) { //待办事项 '保持' 逻辑(例如打开的对话框等) } 别的 [/代码] – justin89