简体   繁体   English

C#应用程序范围内的鼠标左键单击事件

[英]C# Application-Wide Left Mouse Click Event

I want to play a sound when the left mouse button is clicked anywhere in my form without having to place Mouse click events on every single control in the form. 我想在窗体的任意位置单击鼠标左键时播放声音,而不必在窗体的每个控件上放置鼠标单击事件。 Is there a way to accomplish this? 有没有办法做到这一点?

You can detect the Windows notification before it is dispatched to the control with the focus with the IMessageFilter interface. 您可以使用IMessageFilter接口在将Windows通知分发给具有焦点的控件之前对其进行检测。 Make it look similar to this: 使它看起来与此类似:

public partial class Form1 : Form, IMessageFilter {
    public Form1() {
        InitializeComponent();
        Application.AddMessageFilter(this);
        this.FormClosed += delegate { Application.RemoveMessageFilter(this); };
    }

    public bool PreFilterMessage(ref Message m) {
        // Trap WM_LBUTTONDOWN
        if (m.Msg == 0x201) {
            System.Diagnostics.Debug.WriteLine("BEEP!");
        }
        return false;
    }
}

This works for any form in your project, not just the main one. 这适用于您项目中的任何形式,而不仅仅是主要形式。

This should do the trick 这应该可以解决问题

const int WM_PARENTNOTIFY = 0x210;
const int WM_LBUTTONDOWN = 0x201;

protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_LBUTTONDOWN || (m.Msg == WM_PARENTNOTIFY && (int)m.WParam == WM_LBUTTONDOWN)) 
         DoIt();
    base.WndProc(ref m);
}

Case WM_PARENTNOTIFY Select Case Wparam Case 513 ' WM_LBUTTODOWN PlaySoundA End Select Case WM_PARENTNOTIFY选择Case Wparam Case 513'WM_LBUTTODOWN PlaySoundA结束选择

Using For Vb Or Vba 用于Vb或Vba

这个项目可能无法满足您的需求(因为它钩住了全局鼠标事件,而不仅是窗体上的事件),但是我认为它显示了您所需要的基本知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM