我想创建一个纸牌游戏。我使用 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);
我正在寻找一种方法来实现应用程序全局事件处理程序或一种方法来实现所谓的事件冒泡。至少我想让鼠标忽略某些控件。
最佳答案
为了做到这一点,您需要跟踪代码中的一些内容:
- 鼠标指向哪张卡 当按下鼠标按钮时; 这是您想要的卡 移动(使用 MouseDown 事件)
- 当鼠标移动时卡片也随之移动
- 释放鼠标按钮后停止移动卡片(使用 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/