Comment afficher une fenêtre masquée dans l’application Windows Form

la programmation


J’essaie d’afficher la fenêtre masquée dans l’application Windows Form à l’aide de la touche de raccourci. Je peux la masquer mais je ne peux pas l’afficher.
suggère-moi comment je ferais.

Merci
Prafulla

Solution 2

Solution 3

Solution 4

Essaye ça:
Utiliser SurKeydown[^] événement:

C#
private void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
     if (e.Shift && e.KeyCode == Keys.H) 
     {
         WindowState = FormWindowState.Minimized;
     }        
}

Je l’ai trouvé ici[^]

Solution 5

Vous devez vous connecter à l’API win32. Dès que vous masquez votre formulaire .net, les événements et les abonnés aux événements cessent de fonctionner car ils n’existent que dans le conteneur du formulaire. Vous avez besoin de quelque chose comme ça.

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
    }
}

Enregistrez maintenant S et H avec Alt + Shift en appelant et en transmettant un rappel de type Action.

RegisterHoitKey.

Connectez une action pour votre rappel qui affichera ou masquera votre formulaire.

Solution 6

Pour afficher et masquer une fenêtre dans une application Windows Forms à l’aide d’une touche de raccourci, vous pouvez gérer l’événement KeyDown pour détecter le moment où la touche de raccourci est enfoncée. Ensuite, vous pouvez basculer la visibilité du formulaire en conséquence. Voici un exemple de base de la façon dont vous pouvez y parvenir :

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();
                }
            }
        }
    }
}

Dans cet exemple :

Nous sommes abonnés à l’événement KeyDown du formulaire dans le constructeur.
Lorsque la touche de raccourci (dans ce cas, Ctrl + H) est enfoncée, le gestionnaire d’événements MainForm_KeyDown est appelé.
Dans le gestionnaire d’événements, nous basculons la visibilité du formulaire à l’aide de l’indicateur isVisible et des méthodes Show() et Hide().
Assurez-vous de remplacer YourNamespace par l’espace de noms réel de votre application. Vous pouvez également personnaliser la combinaison de touches de raccourci (Ctrl + H dans cet exemple) en modifiant la condition dans le gestionnaire d’événements KeyDown.

コメント

タイトルとURLをコピーしました