c#在任何地方检测鼠标点击(表格内外)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#在任何地方检测鼠标点击(表格内外)相关的知识,希望对你有一定的参考价值。
是否可以在if语句中的任何位置(表单内部和外部)检测鼠标单击(左/右)?如果有可能,怎么样?
if(MouseButtons.LeftButton == MouseButtonState.Pressed){
...
}
答案
如果我理解你需要“从窗外点击”并且Hans Passant的建议不符合您的需求,那么这是一个入门者。您可能需要为Form1_Click添加事件处理程序。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
Mutex checking = new Mutex(false);
AutoResetEvent are = new AutoResetEvent(false);
//You could create just one handler, but this is to show what you need to link to
private void Form1_MouseLeave(object sender, EventArgs e)
{
StartWaitingForClickFromOutside();
}
private void Form1_Leave(object sender, EventArgs e)
{
StartWaitingForClickFromOutside();
}
private void Form1_Deactivate(object sender, EventArgs e)
{
StartWaitingForClickFromOutside();
}
private void StartWaitingForClickFromOutside()
{
if (checking.WaitOne(10))
{
var ctx = new SynchronizationContext();
are.Reset();
Task.Factory.StartNew(() =>
{
while (true)
{
if (are.WaitOne(1))
{
break;
}
if (MouseButtons == MouseButtons.Left)
{
ctx.Send(CLickFromOutside, null);
//you might need to put in a delay here and not break depending on what you want to accomplish
break;
}
}
checking.ReleaseMutex();
});
}
}
private void CLickFromOutside(object state)
{
MessageBox.Show("Clicked from outside of the window");
}
private void Form1_MouseEnter(object sender, EventArgs e)
{
are.Set();
}
private void Form1_Activated(object sender, EventArgs e)
{
are.Set();
}
private void Form1_Enter(object sender, EventArgs e)
{
are.Set();
}
private void Form1_VisibleChanged(object sender, EventArgs e)
{
if (this.Visible == true)
{
are.Set();
}
else
{
StartWaitingForClickFromOutside();
}
}
}
}
如果我不正确地理解你,你可能会觉得这很有用:Pass click event of child control to the parent control
另一答案
当用户在窗体控件外部单击时,它会失去焦点,您可以使用它。这意味着您必须使用窗体控件的_Deactivate(object sender, EventArgs e)
事件才能使其工作。因为当表单失去焦点并且不再是活动表单时将触发。让Form1
成为形式,然后事件将如下:
private void Form1_Deactivate(object sender, EventArgs e)
{
// Your code here to handle this event
}
以上是关于c#在任何地方检测鼠标点击(表格内外)的主要内容,如果未能解决你的问题,请参考以下文章
c#DataGridview 单击选中一行任何地方都可以获取name字段