【问题标题】:MouseMove event doesn't fired with TransparencyKey不使用 TransparencyKey 触发 MouseMove 事件
【发布时间】:2014-08-17 13:15:32
【问题描述】:

我正在创建一个简单的应用程序,它在鼠标之后绘制一条水平线和一条垂直线。

使用 TransparencyKey 使表单透明,使用 Paint 事件绘制线条:

private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Pen pen = new Pen(Color.Lime);
            e.Graphics.DrawLine(pen, 0, py, this.Size.Width, py);
            e.Graphics.DrawLine(pen, px, 0, px, this.Size.Height);
        }

private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            px = e.X; // get cursor X pos
            py = e.Y; // get cursor Y pos
            Invalidate(); // fire Paint event
        }

但 MouseMove 事件仅在鼠标悬停在绘制的线条上时才会触发。如何使表单在​​透明时捕获鼠标事件? (只有鼠标移动,我希望表单仍然可以点击)

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    您可以在此处阅读:http://msdn.microsoft.com/en-us/library/system.windows.forms.form.transparencykey%28v=vs.110%29.aspx - “在表单的透明区域执行的任何鼠标操作,例如单击鼠标,都将传输到透明区域下方的窗口”。实现目标的一种方法是编写自己的方法,该方法将在循环中检查光标相对于表单的位置,这就是我的意思(它对我使用 TransparencyKey,调整大小和移动表单):

    private void MouseMovedWithTransparency()
    {
       Point lastCursorPos = new Point(-1, -1); // Starting point.
       while (this.Visible)
       {
            Point currentCursorPos = Cursor.Position;
            if (this.ContainsFocus && currentCursorPos.X > this.Left && currentCursorPos.X < this.Left + this.Width &&
                currentCursorPos.Y > this.Top && currentCursorPos.Y < this.Top + this.Height)
            {
                if ((currentCursorPos.X != lastCursorPos.X) || (currentCursorPos.Y != lastCursorPos.Y))
                {
                    // Do actions as in MouseMoved event.
    
                    // Save the new position, so it won't be triggered, when user doesn't move the cursor.
                    lastCursorPos = currentCursorPos;
                }
            }
    
            Application.DoEvents(); // UI must be kept responsive.
            Thread.Sleep(1);
        }
    }
    

    您现在要做的就是从 Shown 事件中调用此方法 - this.Visible 必须为真,因此这是使其工作的最简单方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多