Click here to Skip to main content
15,878,748 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to show the hide window in windows form application using shortcut key.I am able to hide but unable to show.
suggest me how would I do.

Thanks
Prafulla
Posted
Updated 4-Sep-12 20:31pm
v2

 
Share this answer
 
v2
Comments
Prafulla Sahu 5-Sep-12 2:37am    
Thanks Joan for your suggestion but I want my solution some what differently.Sorry i didn't mention the exact thing before,here is my requirement:For example take 2 key 'S' for show and 'h' for hide when I will press 'h' key from the keyboard the window should be hide and when I will press 'S' it should be visible
Joan M 5-Sep-12 2:40am    
Then you should edit your question... As you can see you are receiving answers that are not useful for anyone. We (you and us) are loosing time. :(

Anyway, then you need to capture the S and H keys...

See my updated answer...
Prafulla Sahu 5-Sep-12 2:52am    
Thanks Joan I did updated my question
 
Share this answer
 
v2
Comments
Prafulla Sahu 5-Sep-12 2:36am    
Thanks Kishore for your suggestion but I want my solution some what differently.Sorry i didn't mention the exact thing before,here is my requirement:For example take 2 key 'S' for show and 'h' for hide when I will press 'h' key from the keyboard the window should be hide and when I will press 'S' it should be visible
D-Kishore 5-Sep-12 2:41am    
can you share your code
Prafulla Sahu 5-Sep-12 2:50am    
In KeyPress Event of Form1 I am writing
if (e.KeyChar == 's')
{
this.Show();
}
else if (e.KeyChar == 'h')
{
this.Hide();
}
D-Kishore 5-Sep-12 2:54am    
Key press event for what control
D-Kishore 5-Sep-12 2:58am    
The same code is working for me
Try this:
Use OnKeydown[^] event:
C#
private void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
     if (e.Shift && e.KeyCode == Keys.H) 
     {
         WindowState = FormWindowState.Minimized;
     }        
}

Found it here[^]
 
Share this answer
 
Comments
Prafulla Sahu 5-Sep-12 2:47am    
hi Prasad thanks for your suggestion.
I am able to hide the window but unable to show that window after hide operation
Prasad_Kulkarni 5-Sep-12 2:51am    
Prafulla Sahu 7-Sep-12 0:44am    
hi prasad
I have a code line in my Form_Load event that
"this.ShowInTaskbar=false"
If I will comment this line the code is working fine for the shortcut key and if I will uncomment it then it is not working.Sp please suggest me it is giving me so much stress.
Prasad_Kulkarni 7-Sep-12 0:50am    
On page load you're trying to hide your form?

Am not getting what exactly you want Prafulla, can you please explain some more.
Prafulla Sahu 7-Sep-12 1:01am    
My requirement is when my form will run for the very first time it will ask for some settings to filled up, and after that when ever my application will start it should not ask for the settings again and it will go to hide state but it will keep running at the background.Suppose I want to stop my application then I can stop using some shortcut key(I am using Shift+alt+h).
You need to get a hook into the win32 api. As soon as you hide your .net form, the events and event subscribers stop working because they only exist in the container of the form. You need something like this.



C#
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Input;

public class GlobalHotKey : IDisposable
{
  
    public static bool RegisterHotKey(string aKeyGestureString, Action aAction)
    {
        var c = new KeyGestureConverter();
        KeyGesture aKeyGesture = (KeyGesture)c.ConvertFrom(aKeyGestureString);
        return RegisterHotKey(aKeyGesture.Modifiers, aKeyGesture.Key, aAction);
    }

    public static bool RegisterHotKey(ModifierKeys aModifier, Key aKey, Action aAction)
    {
        if (aModifier == ModifierKeys.None)
        {
            throw new ArgumentException("Modifier must not be ModifierKeys.None");
        }
        if (aAction is null)
        {
            throw new ArgumentNullException(nameof(aAction));
        }

        System.Windows.Forms.Keys aVirtualKeyCode = (System.Windows.Forms.Keys)KeyInterop.VirtualKeyFromKey(aKey);
        currentID = currentID + 1;
        bool aRegistered = RegisterHotKey(window.Handle, currentID,
                                    (uint)aModifier | MOD_NOREPEAT,
                                    (uint)aVirtualKeyCode);

        if (aRegistered)
        {
            registeredHotKeys.Add(new HotKeyWithAction(aModifier, aKey, aAction));
        }
        return aRegistered;
    }

    public void Dispose()
    {
        // unregister all the registered hot keys.
        for (int i = currentID; i > 0; i--)
        {
            UnregisterHotKey(window.Handle, i);
        }

        // dispose the inner native window.
        window.Dispose();
    }

    static GlobalHotKey()
    {
        window.KeyPressed += (s, e) =>
        {
            registeredHotKeys.ForEach(x =>
            {
                if (e.Modifier == x.Modifier && e.Key == x.Key)
                {
                    x.Action();
                }
            });
        };
    }

    private static readonly InvisibleWindowForMessages window = new InvisibleWindowForMessages();
    private static int currentID;
    private static uint MOD_NOREPEAT = 0x4000;
    private static List<HotKeyWithAction> registeredHotKeys = new List<HotKeyWithAction>();

    private class HotKeyWithAction
    {

        public HotKeyWithAction(ModifierKeys modifier, Key key, Action action)
        {
            Modifier = modifier;
            Key = key;
            Action = action;
        }

        public ModifierKeys Modifier { get; }
        public Key Key { get; }
        public Action Action { get; }
    }

    // Registers a hot key with Windows.
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
    // Unregisters the hot key with Windows.
    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    private class InvisibleWindowForMessages : System.Windows.Forms.NativeWindow, IDisposable
    {
        public InvisibleWindowForMessages()
        {
            CreateHandle(new System.Windows.Forms.CreateParams());
        }

        private static int WM_HOTKEY = 0x0312;
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == WM_HOTKEY)
            {
                var aWPFKey = KeyInterop.KeyFromVirtualKey(((int)m.LParam >> 16) & 0xFFFF);
                ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);
                if (KeyPressed != null)
                {
                    KeyPressed(this, new HotKeyPressedEventArgs(modifier, aWPFKey));
                }
            }
        }

        public class HotKeyPressedEventArgs : EventArgs
        {
            private ModifierKeys _modifier;
            private Key _key;

            internal HotKeyPressedEventArgs(ModifierKeys modifier, Key key)
            {
                _modifier = modifier;
                _key = key;
            }

            public ModifierKeys Modifier
            {
                get { return _modifier; }
            }

            public Key Key
            {
                get { return _key; }
            }
        }


        public event EventHandler<HotKeyPressedEventArgs> KeyPressed;

        #region IDisposable Members

        public void Dispose()
        {
            this.DestroyHandle();
        }

        #endregion
    }
}




Now register S and H with Alt + Shift by calling and passing in a call back of type Action.


RegisterHoitKey.



Wire up an Action for your call back that will show your form or hide it.
 
Share this answer
 
Comments
Ralf Meier 15-Feb-24 3:40am    
Have you realized that this question is nearly 12 years old ?
I suppose that the OP has allready a Solution ...
If you want to answer questions then please take those which are actuell ...
jb.pearson2 15-Feb-24 21:20pm    
Is it against the rules to post an answer to this? And what about people who come across this in a Google search?
jb.pearson2 15-Feb-24 21:20pm    
And your comment adds no value to the discussion. So why comment?
To show and hide a window in a Windows Forms application using a shortcut key, you can handle the KeyDown event to detect when the shortcut key is pressed. Then, you can toggle the visibility of the form accordingly. Here's a basic example of how you can achieve this:

C#
using System;
using System.Windows.Forms;

namespace YourNamespace
{
    public partial class MainForm : Form
    {
        private bool isVisible = true; // Flag to track the visibility of the form

        public MainForm()
        {
            InitializeComponent();
            this.KeyPreview = true; // Enable key events to be captured by the form
            this.KeyDown += MainForm_KeyDown; // Subscribe to the KeyDown event
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            // Check if the shortcut key (e.g., Ctrl + H) is pressed
            if (e.Control && e.KeyCode == Keys.H)
            {
                // Toggle the visibility of the form
                isVisible = !isVisible;
                
                if (isVisible)
                {
                    // Show the form
                    this.Show();
                }
                else
                {
                    // Hide the form
                    this.Hide();
                }
            }
        }
    }
}

In this example:

We've subscribed to the KeyDown event of the form in the constructor.
When the shortcut key (in this case, Ctrl + H) is pressed, the MainForm_KeyDown event handler is called.
Inside the event handler, we toggle the visibility of the form using the isVisible flag and the Show() and Hide() methods.
Make sure to replace YourNamespace with the actual namespace of your application. You can also customize the shortcut key combination (Ctrl + H in this example) by modifying the condition in the KeyDown event handler.
 
Share this answer
 
Comments
Ralf Meier 15-Feb-24 3:40am    
Have you realized that this question is nearly 12 years old ?
I suppose that the OP has allready a Solution ...
If you want to answer questions then please take those which are actuell ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900