我有一个Windows窗体应用程序与F键的一些按钮。当你将鼠标放在按钮上时变成灰色,当你点击它们时,会变得略带灰色。我想用F键击键模仿这种行为......你会怎么做?模拟平面按钮鼠标MouseDown和MouseOver
1
A
回答
1
最后我实现了按钮更改背景:
class FunctionButton : Button
{
private Color m_colorOver;
private bool m_isPressed;
public FunctionButton() : base()
{
m_isPressed = false;
}
protected override void OnGotFocus(EventArgs e)
{
OnMouseEnter(null);
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
if (!m_isPressed)
{
OnMouseLeave(null);
}
base.OnLostFocus(e);
}
protected override void OnMouseLeave(EventArgs e)
{
if (!Focused && !m_isPressed)
{
base.OnMouseLeave(e);
}
}
public void FunctionKeyPressed()
{
// Handle just the first event
if (!m_isPressed)
{
m_isPressed = true;
m_colorOver = FlatAppearance.MouseOverBackColor;
FlatAppearance.MouseOverBackColor = FlatAppearance.MouseDownBackColor;
OnMouseEnter(null);
PerformClick();
}
}
public void FunctionKeyReleased()
{
m_isPressed = false;
FlatAppearance.MouseOverBackColor = m_colorOver;
if (Focused)
{
OnMouseEnter(null);
}
else
{
base.OnMouseLeave(null);
}
}
}
这不是最干净的方式,但它工作得很好。我希望更多的例子以更清洁和更优雅的风格来做到这一点。
1
3
设置窗体的KeyPreview
属性true
,处理KeyDown
和KeyUp
事件,跟踪哪些功能键(S)被挤压,并调用Invalidate
方法对每个键的按钮去向上或向下。
然后,处理按钮的Paint
事件,并且如果其按键处于关闭状态,则使用ButtonRenderer
class来绘制按钮,就好像按下按钮一样。
+0
我会尝试这样的事情。谢谢! – yeyeyerman 2009-08-20 08:28:52
+0
我不工作,因为您无法使用ButtonRenderer渲染平面按钮:-o – yeyeyerman 2009-08-20 15:21:10
0
SetCapture和ReleaseCapture可能工作。
高这个问题 http://stackoverflow.com/questions/1304714/simulating-a-click-with-the-keyboard-in-windows-forms – yeyeyerman 2009-08-20 14:13:13