c# - 如何为鼠标创建一个控件 "transparent"或将MouseMove事件路由到父级?

标签 c# winforms controls mouse

我想创建一个纸牌游戏。我使用 mousemove 事件将卡片拖过窗口。问题是,如果我将鼠标移到另一张卡上,它会被卡住,因为鼠标光标下方的卡获取鼠标事件,因此不会触发窗口的 MouseMove 事件。

这就是我所做的:

 private void RommeeGUI_MouseMove(object sender, MouseEventArgs e)
 {
      if (handkarte != null)
      {
                handkarte.Location = this.PointToClient(Cursor.Position);
      }
 }

我尝试了以下方法,但没有任何区别:

SetStyle(ControlStyles.UserMouse,true);
SetStyle(ControlStyles.EnableNotifyMessage, true);

我正在寻找一种方法来实现应用程序全局事件处理程序或一种方法来实现所谓的事件冒泡。至少我想让鼠标忽略某些控件。

最佳答案

为了做到这一点,您需要跟踪代码中的一些内容:

  1. 鼠标指向哪张卡 当按下鼠标按钮时; 这是您想要的卡 移动(使用 MouseDown 事件)
  2. 当鼠标移动时卡片也随之移动
  3. 释放鼠标按钮后停止移动卡片(使用 MouseUp 事件)

为了仅移动控件,无需实际捕获鼠标。

一个简单的示例(使用面板控件作为“卡片”):

Panel _currentlyMovingCard = null;
Point _moveOrigin = Point.Empty;
private void Card_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        _currentlyMovingCard = (Panel)sender;
        _moveOrigin = e.Location;
    }
}

private void Card_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left && _currentlyMovingCard != null)
    {
        // move the _currentlyMovingCard control
        _currentlyMovingCard.Location = new Point(
            _currentlyMovingCard.Left - _moveOrigin.X + e.X,
            _currentlyMovingCard.Top - _moveOrigin.Y + e.Y);
    }
}

private void Card_MouseUp(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left && _currentlyMovingCard != null)
    {
        _currentlyMovingCard = null;
    }
}

关于c# - 如何为鼠标创建一个控件 "transparent"或将MouseMove事件路由到父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/931911/

相关文章:

c# - 使用循环初始化多个对象

c# - 为什么 C 和 C++ 中的 float / double 没有除余运算?

c# - unity 为什么我的视频播放器上没有播放音频?

c# - 创建 .NET 窗体时 Visual Studio 指定的窗口类名称是什么?

c# - 从内部 for 循环中中断封闭的 switch 语句?

.NET 图表控件 - X 轴文本旋转

c# 当我将控件添加到面板时,控件变为 NULL

c# - 为什么非静态类中有所有静态方法/变量?

c# - 从子控件访问父控件元素的最佳方法是什么?

c# - 更改 DataGridViewCell 用户输入处理行为