2009-08-19 50 views
1

我有一个Windows窗体应用程序与F键的一些按钮。当你将鼠标放在按钮上时变成灰色,当你点击它们时,会变得略带灰色。我想用F键击键模仿这种行为......你会怎么做?模拟平面按钮鼠标MouseDown和MouseOver

+0

高这个问题 http://stackoverflow.com/questions/1304714/simulating-a-click-with-the-keyboard-in-windows-forms – yeyeyerman 2009-08-20 14:13:13

回答

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

使用Button.PerformClick()。

+1

调用功能,但图形状态有关该按钮不会改变。 – yeyeyerman 2009-08-19 11:10:50

3

设置窗体的KeyPreview属性true,处理KeyDownKeyUp事件,跟踪哪些功能键(S)被挤压,并调用Invalidate方法对每个键的按钮去向上或向下。

然后,处理按钮的Paint事件,并且如果其按键处于关闭状态,则使用ButtonRenderer class来绘制按钮,就好像按下按钮一样。

+0

我会尝试这样的事情。谢谢! – yeyeyerman 2009-08-20 08:28:52

+0

我不工作,因为您无法使用ButtonRenderer渲染平面按钮:-o – yeyeyerman 2009-08-20 15:21:10