简体   繁体   中英

How can I make my Form visible/invisible by pressing insert?

I'm trying to find out how to making my form invisible when I press insert and when I press insert again it makes the form visible. I try to find out how, but no one seems to have what I am looking for.

A simple example how you can manipulate Form's visibility by handling the Insert key down:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        // Don't forget to enable Form.KeyPreview in order to receive key down events
        if (e.KeyCode == Keys.Insert)
        {
            Visible = false;
        }
    }
}

You can set Visible back to true to make it visible. However, you will not be able to do this, because Form became invisible and doesn't receive key down events anymore. In this case you can try to set the global hotkey using, for example, the GlobalHotKey library described here . Note also, that it doesn't make sense to set a single key (eg Insert) as global hotkey as in most cases system or another application will capture it.

You can do this:

private void InfoForm_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Insert) Opacity = Opacity == 0 ? 1 : 0;
}

For this to work you need to turn on the Form's KeyPreview property!

But turning visiblity back on (or to be precise turning off opacity) will only work if no other program has received focus in the meantime.

If that might happen you need to set a global keyboard hook ; make sure to pass the Insert key back on or else many other programms will no longer work right.. All in all I would not recommend it..

I'm not sure when the whole idea might make sense. One answer could be to show or hide a popup data window that is only meant to show some additional information popping up from a base data window.

In that case you could simply close the window whenever it gets deactivated:

private void InfoForm_Deactivate(object sender, EventArgs e)
{
    this.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM