我尝试在 Windows 窗体中玩数独游戏。该功能就像有 81 个按钮(减去给定的图块),在其他图块上,我希望在悬停时在小按钮中显示从 1 到 9 的数字。
我的问题是,因为您在 1 到 9 按钮上,显然没有将鼠标悬停在“主字段按钮”上,即使它们是在内部创建的。
有什么建议吗?
虽然可能有更简单的方法来实现这个程序,并且可能不需要将按钮放在相同的位置,但是根据您的需要,如果两个按钮在表单中重叠,可以使用以下方法,即“OnMouseHover”方法两个按钮都可以调用。
假设按钮的名称是“TopButton”和“UnderlyingButton”。如果我们将以下行放入“TopButton_MouseHover”中,通过将鼠标移动到顶部按钮上,将找到另一个按钮并执行其“MouseHover”:
FindUnderlyingButtonsAndRaiseOnMouseHover(sender, e);
程序如下:
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private List<DesiredType> GetListOfUnderlyingControls<DesiredType>(DesiredType TopControl) where DesiredType: Control
{
var listOfUnderlyingControls = new List<DesiredType>();
var CenterPointOfTopControl = new Point((TopControl.Left + TopControl.Right) / 2, (TopControl.Top + TopControl.Bottom) / 2);
foreach (Control UnderlyingControl in Controls)
if (
(UnderlyingControl.GetType() == typeof(DesiredType)) &&
(UnderlyingControl.Name != TopControl.Name) &&
UnderlyingControl.Bounds.Contains(CenterPointOfTopControl)
)
listOfUnderlyingControls.Add((DesiredType)UnderlyingControl);
return listOfUnderlyingControls;
}
private void FindUnderlyingButtonsAndRaiseOnMouseHover(object sender, EventArgs e)
{
var ListOfUnderlyingButtons = GetListOfUnderlyingControls((Button)sender);
foreach (var UnderlyingButton in ListOfUnderlyingButtons)
{
var OnMouseHoverEventHandler = UnderlyingButton.GetType().GetMethod("OnMouseHover", BindingFlags.Instance | BindingFlags.NonPublic);
if (OnMouseHoverEventHandler != null)
OnMouseHoverEventHandler.Invoke(UnderlyingButton, new object[] { e });
}
}
private void TopButton_MouseHover(object sender, EventArgs e)
{
FindUnderlyingButtonsAndRaiseOnMouseHover(sender, e);
}
private void UnderlyingButton_MouseHover(object sender, EventArgs e)
{
}
}