c# - 鼠标事件未触发

标签 c# mouseevent mousemove mouseclick-event

我正在制作一个 C# WinForms 应用程序。由于某种原因,窗体的 MouseMove 和 MouseClick 事件没有被触发。 (当我发现原因时,我可能会觉得自己像个白痴。) 它是一种透明形式(TransparencyKey 设置为背景色),在 Picture Box 中带有半透明动画 gif。我正在制作屏幕保护程序。 有什么建议吗?

编辑: 主屏幕保护程序.cs

    Random randGen = new Random();
    public MainScreensaver(Rectangle bounds)
    {
        InitializeComponent();
        this.Bounds = Bounds;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Rectangle screen = Screen.PrimaryScreen.Bounds;
        Point position = new Point(randGen.Next(0,screen.Width-this.Width)+screen.Left,randGen.Next(0,screen.Height-this.Height)+screen.Top);
        this.Location = position;
    }

    private void MainScreensaver_Load(object sender, EventArgs e)
    {
        Cursor.Hide();
        TopMost = true;
    }
    private Point mouseLocation;

    private void MainScreensaver_MouseMove(object sender, MouseEventArgs e)
    {
        if (!mouseLocation.IsEmpty)
        {
            // Terminate if mouse is moved a significant distance
            if (Math.Abs(mouseLocation.X - e.X) > 5 ||
                Math.Abs(mouseLocation.Y - e.Y) > 5)
                Application.Exit();
        }

        // Update current mouse location
        mouseLocation = e.Location;
    }

    private void MainScreensaver_KeyPress(object sender, KeyPressEventArgs e)
    {
        Application.Exit();
    }

    private void MainScreensaver_Deactive(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void MainScreensaver_MouseClick(object sender, MouseEventArgs e)
    {
        Application.Exit();
    }

摘自 MainScreensaver.Designer.cs InitialiseComponent()

    this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainScreensaver_MouseClick);
    this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.MainScreensaver_MouseMove);

最佳答案

这不是您问题的答案,但我会留下这个答案,以防其他人在尝试调试同一问题时偶然发现这个问题(这就是我来到这里的原因)

在我的例子中,我有一个派生自 Form 的类。

我也在使用 TransparencyKey

我注意到的一些事情

  • 事件不会在表单的透明部分触发。
  • 如果鼠标光标位于窗体上的另一个控件上,则不会触发事件。
  • 如果您覆盖 WndProc 并设置 WM_NCHITTEST 消息的结果,则事件不会触发。 Windows 甚至不发送会导致 .NET 事件的相应鼠标消息。

我的解决方案

在我的构造函数中,我忘记调用 InitializeComponent()

这是事件处理程序绑定(bind)到我的控件的地方。

事件没有触发,因为处理程序没有被绑定(bind)。

关于c# - 鼠标事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239542/

相关文章:

c# - 为什么我的证书集合中存在 .Pfx 而不是我的 .Cer?

c# - 将 C# 代码从 Cassandra .5 迁移到 .6

C# 如何在按住鼠标按钮时循环

javascript - Mousemove 延迟触发 mouseleave 事件

javascript - 触发JavaScript mousemove而不移动鼠标但获取鼠标坐标

c - 指针运动。为什么数字这么高?为什么它以 block 而不是恒定流的形式打印信息?

c# - 这真的是 Async 吗? IEnumerable<T> 扩展

c# - 在 C# 中从内存流保存为 jpeg

python - 使用 (Python) Webdriver 在不使用元素的情况下选择文本(即单击并拖动以突出显示从一组坐标到另一组坐标)

Java SWT : MouseTrackListener only fires events when the shell is focused