C#中如何判断一个窗体中鼠标左键按下超过三秒?

如题
2024-11-20 06:25:55
推荐回答(3个)
回答(1):

long lastMouseDown; //局部变量

Public Form1() //窗体的构造函数
{
this.MouseDown += (object sender, MouseEventArgs e) =>
{
if (e.Button == MouseButtons.Left) lastMouseDown = DateTime.Now.Ticks;
else lastMouseDown = 0;
};
this.MouseUp += (object sender, MouseEventArgs e) =>
{
if (e.Button == MouseButtons.Left && lastMouseDown > 0)
{
TimeSpan p = new TimeSpan(DateTime.Now.Ticks - lastMouseDown);
if (p.TotalSeconds > 3)
{
MessageBox.Show("鼠标按下了 "+p.TotalSeconds+" 秒!");
}
lastMouseDown = 0;
}
};
}

回答(2):

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_MouseDownTimer = new Timer();
_MouseDownTimer.Interval = 3000;
_MouseDownTimer.Tick += new EventHandler( OnMouseDownTimer_Tick );
}

void OnMouseDownTimer_Tick( object sender, EventArgs e )
{
_MouseDownTimer.Stop();
MessageBox.Show( "按下鼠标左键3秒。" );
}

private Timer _MouseDownTimer;

private void Form1_MouseDown( object sender, MouseEventArgs e )
{
if ( e.Button == MouseButtons.Left )
{
_MouseDownTimer.Start();
}
}

private void Form1_MouseUp( object sender, MouseEventArgs e )
{
if ( e.Button == MouseButtons.Left )
{
if ( _MouseDownTimer.Enabled ) _MouseDownTimer.Stop();
}
}
}

回答(3):

放个Timer控件
当MouseDown的时候开始计时
然后么你应该会了吧