从鼠标悬停获取按钮在网格中的位置(C# VS)
Getting location of button in grid from Mousehover (C# VS)
在学校里,我目前正在为 AP Comp Sci 开发一款战舰游戏,我一直在努力做到这一点,以便在船舶放置阶段,一个图片框(一艘船)将位置更改为按钮所在的位置鼠标恰好在上方盘旋。这应该像幽灵图标一样用于放置船舶的位置。这些按钮位于一个数组中,因为它们是使用 2D forloop 在网格中制作的。
我不知道如何让 MouseHover 从按钮数组中获取按钮位置。这主要是因为我不知道如何将数组中按钮位置的 x y 值提供给 MouseHover 方法。
我尝试使用计时器检查数组中的每个按钮是否有焦点,并成功将图片框的位置更改为该按钮:
private void MouseXYCheckTimer_Tick_1(object sender, EventArgs e)
{
for (int x = 0; x < 15; x++)
{
for (int y = 0; y < 15; y++)
{
if (b[x, y].Focused)
{
ShipImage1.Location = b[x, y].Location;
}
}
}
}
然而,这需要单击按钮以使其获得焦点(从而放置飞船),从而违背了目的。
我已经在 MouseHover 上仔细查看了不同的帖子,但仍然无法解决我的问题,将不胜感激。谢谢!
有用于处理 MouseEnter 的内置事件
// Wire up the MouseEnter event when creating your buttons
button.MouseEnter += button_MouseEnter;
// Method that gets called
private void button_MouseEnter(object sender, EventArgs e)
{
var button = sender as Button;
ShipImage1.Location = button.Location;
}
如果我理解正确,假设您使用的是 Winforms,您只需将图片位置逻辑订阅到每个按钮的 MouseMove
事件。所以请尝试以下操作:
在您的 class:
中定义此方法
private void button_MouseMove(object sender, MouseEventArgs e)
{
ShipImage1.Location = e.Location;
}
然后在负责创建存储到 b
数组中的每个按钮实例的逻辑中,将该方法订阅到 MouseMove
事件:
...
for (int x = 0; x < 15; x++)
{
for (int y = 0; y < 15; y++)
{
var myButton = new Button();
myButton.MouseMove += button_MouseMove;
// More awesome stuff around myButton...
b[x, y] = myButton;
}
}
...
此外,如果需要,您可以从 Form.MousePosition
静态 属性.
获取当前屏幕鼠标坐标
祝你好运!
编辑
或者使用另一个答案中@Jerry 所指示的 MouseEnter
事件,这应该会更好。
在学校里,我目前正在为 AP Comp Sci 开发一款战舰游戏,我一直在努力做到这一点,以便在船舶放置阶段,一个图片框(一艘船)将位置更改为按钮所在的位置鼠标恰好在上方盘旋。这应该像幽灵图标一样用于放置船舶的位置。这些按钮位于一个数组中,因为它们是使用 2D forloop 在网格中制作的。
我不知道如何让 MouseHover 从按钮数组中获取按钮位置。这主要是因为我不知道如何将数组中按钮位置的 x y 值提供给 MouseHover 方法。
我尝试使用计时器检查数组中的每个按钮是否有焦点,并成功将图片框的位置更改为该按钮:
private void MouseXYCheckTimer_Tick_1(object sender, EventArgs e)
{
for (int x = 0; x < 15; x++)
{
for (int y = 0; y < 15; y++)
{
if (b[x, y].Focused)
{
ShipImage1.Location = b[x, y].Location;
}
}
}
}
然而,这需要单击按钮以使其获得焦点(从而放置飞船),从而违背了目的。
我已经在 MouseHover 上仔细查看了不同的帖子,但仍然无法解决我的问题,将不胜感激。谢谢!
有用于处理 MouseEnter 的内置事件
// Wire up the MouseEnter event when creating your buttons
button.MouseEnter += button_MouseEnter;
// Method that gets called
private void button_MouseEnter(object sender, EventArgs e)
{
var button = sender as Button;
ShipImage1.Location = button.Location;
}
如果我理解正确,假设您使用的是 Winforms,您只需将图片位置逻辑订阅到每个按钮的 MouseMove
事件。所以请尝试以下操作:
在您的 class:
中定义此方法private void button_MouseMove(object sender, MouseEventArgs e)
{
ShipImage1.Location = e.Location;
}
然后在负责创建存储到 b
数组中的每个按钮实例的逻辑中,将该方法订阅到 MouseMove
事件:
...
for (int x = 0; x < 15; x++)
{
for (int y = 0; y < 15; y++)
{
var myButton = new Button();
myButton.MouseMove += button_MouseMove;
// More awesome stuff around myButton...
b[x, y] = myButton;
}
}
...
此外,如果需要,您可以从 Form.MousePosition
静态 属性.
祝你好运!
编辑
或者使用另一个答案中@Jerry 所指示的 MouseEnter
事件,这应该会更好。