Hide form using F1 key C #

1

I have form more precisely a menu of options and wanted to hide this form when I pressed the F1 key and showed when I pressed F1 again. I tried following this tutorial from the link using hook keyboard .

However, when I press F1 it hides, but it shows immediately without being hidden. For my case I do not want to use 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();
    }
    
asked by anonymous 27.02.2017 / 03:52

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 occurring because the KeyDown event is triggered when you press a key, and the KeyUp event occurs when you release it.

So basically when you press he was hiding, but it was already showing when you release the key.

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

    
27.02.2017 / 12:49