Hide form using F1 key C#

Asked

Viewed 73 times

1

I have form more precisely a menu of options and wanted to hide that form when I press the key F1 and show when to squeeze F1 again. I tried to follow this tutorial of the link that uses hook keyboard.

But when I squeeze F1 it hides, but already shows next without getting hidden. For my case I do not want to use the Event KeyDown, I need to use this hook.

    public Form1()
    {
        InitializeComponent();            
    }

    globalKeyboardHook gkh = new globalKeyboardHook();

    private void Form1_Load(object sender, EventArgs e)
    {
        gkh.HookedKeys.Add(Keys.F1);

        gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);

        // gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
    }

    void gkh_KeyUp(object sender, KeyEventArgs e)
    {
        this.Show();
        e.Handled = true;            
    }

    void gkh_KeyDown(object sender, KeyEventArgs e)
    {
        this.Hide();
        e.Handled = true;
    }

    private void Form1_Closing(object sender, EventArgs e)
    {
        gkh.unhook();
    }
  • F1 is standard key for HELP, it would not be a mistake to use it like this?

1 answer

1

Hello, try the following:

private bool IsHide { get; set; } 

/*O Evento gkh_KeyUp pode ser removido, eu apenas comentei
 void gkh_KeyUp(object sender, KeyEventArgs e)
{
   this.Show();
   e.Handled = true;


}*/

void gkh_KeyDown(object sender, KeyEventArgs e)
{
    if(!this.IsHide)
       this.Hide();
    else
       this.Show();
    this.IsHide = !this.IsHide
    e.Handled = true;
}

This is happening because the event Keydown is fired when you press a key, and the Keyup occurs when you release her.

So basically when you press he was hiding, but already showed at the release of the key.

In the above code we just create a control variable to know what we should do with the form.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.