C# Winforms: programatically display Button's Hover State

爱⌒轻易说出口 提交于 2019-12-11 02:06:15

问题


i am displaying a numeral keypad in on a winform to enter code. i am displaying nummpad with buttons... The users will be using only keyboards numpad to enter the code\password\? but off-course you can use mouse...

If we use mouse to click button we get a blue-ish effect to display hover & down states..

i was thinking if i can somehow programatically display the down-state of a button according to he key that user pressed on the numpad... HOW TO


回答1:


It is not possible to simulate this behavior by using the default implementation of the button class. However, you can sub class the button to add this behavior:

   public class KeyboardButton : Button
    {
        public void SimulateButtonDown()
        {
            this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
        }

        public void SimulateButtonUp()
        {
            this.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 0, 1, 1, 0));
        }
    }

When you call SimulateButtonDown the button will go into a (visual) state imitating that mouse would have been clicked (and held) on the button. You can implement methods like these for hover events as well.




回答2:


Not an automatic way in doing it, but you can do in code: Crete a class for carrying the user key interaction, and create a Queue of this class. When the user press a key enqueue two of this objects signaling the down/up and key info. Then lets create a winform timer in your form, consuming the queue. For each "event" in the queue up or down, change the button appareance as you please. Having the window timer lets your animation message friendly, so you should actually see the button changing. Try with a 100ms timer. This is a sort of "do-it-yourself" animation.



来源:https://stackoverflow.com/questions/5441089/c-sharp-winforms-programatically-display-buttons-hover-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!