[英]Detect if pressing a mouse button and which WinForm c#
我不想點擊按鈕或表單,我只想知道當光標在表單中時用戶是否按下了鼠標左鍵。
我試過這個:
private void PlayForm_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.LButton)
{
...
}
}
但它不起作用。
我也試過PlayForm_Click()
但它只有當點擊在“畫布”上時才有效,如果頂部還有其他東西,它就不起作用
如果您只想知道在 Form 中執行其他一些代碼時鼠標左鍵是否按下,您可以查看靜態屬性Control.MouseButtons
,它從MouseButtons
枚舉返回一個值。例如:
if ((Control.MouseButtons & MouseButtons.Left) != 0)
您可以使用鼠標輸入/離開來設置鼠標光標位於表單上方的布爾值,然后您可以使用鼠標。
...
bool mouseOverMe;
public MainWindow()
{
InitializeComponent();
mouseOverMe = false;
}
private void Window_MouseEnter(object sender, MouseEventArgs e)
{
mouseOverMe = true;
}
private void Window_MouseLeave(object sender, MouseEventArgs e)
{
mouseOverMe = false;
}
void doSomething()
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
if (mouseOverMe)
MessageBox.Show("Im a mouse down in the window");
}
...
有點像這樣。
據我所知,您需要一個處理程序來單擊表單中的任何內容。 我建議您可以在Form_Load
事件上遍歷表單中的所有控件,並為.Controls
集合中的所有控件設置一個通用處理程序,用於MouseClick
(或 KeyPressed 或您想要的任何事件,根據您當前的需要)加載表單的那一刻,您應該為表單本身注冊相同的處理程序(又名this.MouseClick
)。 如果您以后想為特定控件注冊一個 MouseClick 處理程序,這將有點矯枉過正,但您始終可以比較sender
對象並從那里獲取數據。 示例代碼暫時不存在,因為我是用手機打字的。 稍后會更新。
主要問題是當消息直接發送到子控件時,表單沒有收到任何消息。
解決此問題的一種方法是注冊應用程序范圍的消息過濾器。 請注意,以下實現相當低效(而且相當丑陋),但它應該向您展示基本思想:
void Main()
{
var form = new Form();
form.Load += (s, _) => Application.AddMessageFilter(new MyFilter((Form)s));
var pnl = new Panel();
pnl.Controls.Add(new Button());
form.Controls.Add(pnl);
Application.Run(form);
}
public class MyFilter : IMessageFilter
{
Form form;
public MyFilter(Form form)
{
this.form = form;
this.form.Disposed += (_, __) => Application.RemoveMessageFilter(this);
}
public bool PreFilterMessage(ref Message msg)
{
const int WM_LMOUSEDOWN = 0x0201;
if (msg.Msg == WM_LMOUSEDOWN && msg.HWnd != IntPtr.Zero
&& Control.FromHandle(msg.HWnd).TopLevelControl == form)
{
Console.WriteLine("Hi!");
}
return false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.