Accueil > > > CRÉEZ VOS PROPRES RACCOURCIS CLAVIER AU NIVEAU SYSTÈME
CRÉEZ VOS PROPRES RACCOURCIS CLAVIER AU NIVEAU SYSTÈME
Information sur la source
Description
Parfois on a besoin de créer des raccourcis clavier pour des fonctions de notre application qui puissent être appelés sans que celle-ci soit active. Pour cela, vous devez enregistrer auprès du système des raccourcis globaux, voici une classe qui gère ça pour vous, simplement. EDIT : La fenêtre de votre application n'est pas obligée de contenir le focus pour répondre au raccourcis. EDIT 2 : Cette source est relayée par la newsletter MSDN 23/08/2005 : "Votre avis est important !"
Source
- using System;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- using System.Collections;
-
- namespace CSUtils.Classes
- {
- /// <summary>
- /// Description résumée de Hotkey.
- /// </summary>
- public class HotKey : NativeWindow
- {
- private const int WM_HOTKEY = 0x312;
-
- /// <summary>
- /// HotKeyModifiers énumération
- /// </summary>
- [Flags]
- public enum HotKeyModifiers : int {
- Alt = 0x1,
- Control = 0x2,
- Shift = 0x4,
- Win = 0x8
- }
-
- private struct HotKeyData {
- public Keys Key;
- public HotKeyModifiers Modifiers;
- public IntPtr AtomID;
-
- public static HotKeyData Empty = new HotKeyData();
-
- public HotKeyData(Keys key, HotKeyModifiers modifiers, IntPtr atomId) {
- this.Key = key;
- this.Modifiers = modifiers;
- this.AtomID = atomId;
- }
-
- public override string ToString() {
- return Modifiers.ToString() + "+" + Key.ToString();
- }
-
- public override int GetHashCode() {
- return base.GetHashCode ();
- }
-
- public override bool Equals(object obj) {
- return this.AtomID.Equals (obj);
- }
-
- }
-
-
- private ArrayList hotkeys;
- private Form owner;
-
- public delegate void HotKeyHandler(object sender, HotKeyArgs args);
- public event HotKeyHandler HotKeyPress;
-
- public HotKey(Form owner) {
- this.AssignHandle(owner.Handle);
- this.owner = owner;
- owner.HandleCreated += new EventHandler(owner_HandleCreated);
-
- hotkeys = new ArrayList();
- }
-
- public void RegisterHotKey(Keys key, HotKeyModifiers modifiers) {
- if (!FindHotKey(key, modifiers).Equals(HotKeyData.Empty)) {
- this.registerHotKey(key, modifiers);
- }
- }
-
- public void UnregisterHotKey(Keys key, HotKeyModifiers modifiers) {
- HotKeyData hkData = FindHotKey(key, modifiers);
-
- if (!hkData.Equals(HotKeyData.Empty)) {
- unregisterHotKey(hkData);
- hotkeys.Remove(hkData);
- }
- }
-
- private HotKeyData FindHotKey(Keys key, HotKeyModifiers modifiers) {
- HotKeyData hkData;
- for (int i=0; i<this.hotkeys.Count; i++) {
- hkData = (HotKeyData)hotkeys[i];
- if (hkData.Key == key && hkData.Modifiers == modifiers) {
- return hkData;
- }
- }
-
- return HotKeyData.Empty;
- }
-
- protected override void WndProc(ref Message m) {
- base.WndProc (ref m);
- HotKeyData hkData;
- if (m.Msg == WM_HOTKEY) {
- for (int i=0; i<hotkeys.Count; i++) {
- hkData = (HotKeyData)hotkeys[i];
- if (hkData.Equals(m.WParam)) {
- if (this.HotKeyPress != null) {
- HotKeyPress(this.owner,
- new HotKeyArgs(hkData.Key, hkData.Modifiers));
- }
- break;
- }
- }
- }
- }
-
-
- /// <summary>
- /// Destructeur de la classe.
- /// Il faut libérer les raccourcis créés
- /// </summary>
- ~HotKey() {
- HotKeyData hkData;
- for (int i=hotkeys.Count-1; i>=0; i--) {
- hkData = (HotKeyData)hotkeys[i];
- this.unregisterHotKey(hkData);
- }
- }
-
- #region P/Invoke
- [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
- private static extern IntPtr GlobalAddAtom(string lpString);
-
- [DllImport("kernel32.dll", SetLastError=true, ExactSpelling=true)]
- private static extern IntPtr GlobalDeleteAtom(IntPtr nAtom);
-
- [DllImport("user32.dll")]
- private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
-
- [DllImport("user32.dll")]
- private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
- #endregion
-
- private void registerHotKey(Keys key, HotKeyModifiers modifiers) {
- string atomName = string.Empty;
- IntPtr atomId;
- atomName = key.ToString() + modifiers.ToString() + Environment.TickCount.ToString();
- if (atomName.Length > 255) {
- atomName = atomName.Substring(0,255);
- }
-
- atomId = GlobalAddAtom(atomName);
- if (atomId == IntPtr.Zero) {
- throw new Exception("Impossible d'enregistrer l'atome du raccourci !");
- }
-
- if (!RegisterHotKey(this.Handle, atomId.ToInt32(), (int)modifiers, (int)key)) {
- GlobalDeleteAtom(atomId);
- throw new Exception("Impossible d'enregistrer le raccourci !");
- }
-
- this.hotkeys.Add(new HotKeyData(key, modifiers, atomId));
- }
-
- private void unregisterHotKey(HotKeyData hk) {
- UnregisterHotKey(this.Handle, hk.AtomID.ToInt32());
- GlobalDeleteAtom(hk.AtomID);
- }
-
-
- private void owner_HandleCreated(object sender, EventArgs e) {
- this.AssignHandle(owner.Handle);
- }
- }
-
- #region Classe HotKeyArgs
- public class HotKeyArgs : EventArgs {
- public HotKeyArgs(Keys key, HotKey.HotKeyModifiers modifiers) {
- this.modifiers = modifiers;
- this.key = key;
- }
-
- private Keys key;
- public Keys Key {
- get {return key;}
- }
-
- private HotKey.HotKeyModifiers modifiers;
- public HotKey.HotKeyModifiers Modifiers {
- get {return modifiers;}
- }
- }
- #endregion
- }
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Collections;
namespace CSUtils.Classes
{
/// <summary>
/// Description résumée de Hotkey.
/// </summary>
public class HotKey : NativeWindow
{
private const int WM_HOTKEY = 0x312;
/// <summary>
/// HotKeyModifiers énumération
/// </summary>
[Flags]
public enum HotKeyModifiers : int {
Alt = 0x1,
Control = 0x2,
Shift = 0x4,
Win = 0x8
}
private struct HotKeyData {
public Keys Key;
public HotKeyModifiers Modifiers;
public IntPtr AtomID;
public static HotKeyData Empty = new HotKeyData();
public HotKeyData(Keys key, HotKeyModifiers modifiers, IntPtr atomId) {
this.Key = key;
this.Modifiers = modifiers;
this.AtomID = atomId;
}
public override string ToString() {
return Modifiers.ToString() + "+" + Key.ToString();
}
public override int GetHashCode() {
return base.GetHashCode ();
}
public override bool Equals(object obj) {
return this.AtomID.Equals (obj);
}
}
private ArrayList hotkeys;
private Form owner;
public delegate void HotKeyHandler(object sender, HotKeyArgs args);
public event HotKeyHandler HotKeyPress;
public HotKey(Form owner) {
this.AssignHandle(owner.Handle);
this.owner = owner;
owner.HandleCreated += new EventHandler(owner_HandleCreated);
hotkeys = new ArrayList();
}
public void RegisterHotKey(Keys key, HotKeyModifiers modifiers) {
if (!FindHotKey(key, modifiers).Equals(HotKeyData.Empty)) {
this.registerHotKey(key, modifiers);
}
}
public void UnregisterHotKey(Keys key, HotKeyModifiers modifiers) {
HotKeyData hkData = FindHotKey(key, modifiers);
if (!hkData.Equals(HotKeyData.Empty)) {
unregisterHotKey(hkData);
hotkeys.Remove(hkData);
}
}
private HotKeyData FindHotKey(Keys key, HotKeyModifiers modifiers) {
HotKeyData hkData;
for (int i=0; i<this.hotkeys.Count; i++) {
hkData = (HotKeyData)hotkeys[i];
if (hkData.Key == key && hkData.Modifiers == modifiers) {
return hkData;
}
}
return HotKeyData.Empty;
}
protected override void WndProc(ref Message m) {
base.WndProc (ref m);
HotKeyData hkData;
if (m.Msg == WM_HOTKEY) {
for (int i=0; i<hotkeys.Count; i++) {
hkData = (HotKeyData)hotkeys[i];
if (hkData.Equals(m.WParam)) {
if (this.HotKeyPress != null) {
HotKeyPress(this.owner,
new HotKeyArgs(hkData.Key, hkData.Modifiers));
}
break;
}
}
}
}
/// <summary>
/// Destructeur de la classe.
/// Il faut libérer les raccourcis créés
/// </summary>
~HotKey() {
HotKeyData hkData;
for (int i=hotkeys.Count-1; i>=0; i--) {
hkData = (HotKeyData)hotkeys[i];
this.unregisterHotKey(hkData);
}
}
#region P/Invoke
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern IntPtr GlobalAddAtom(string lpString);
[DllImport("kernel32.dll", SetLastError=true, ExactSpelling=true)]
private static extern IntPtr GlobalDeleteAtom(IntPtr nAtom);
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
#endregion
private void registerHotKey(Keys key, HotKeyModifiers modifiers) {
string atomName = string.Empty;
IntPtr atomId;
atomName = key.ToString() + modifiers.ToString() + Environment.TickCount.ToString();
if (atomName.Length > 255) {
atomName = atomName.Substring(0,255);
}
atomId = GlobalAddAtom(atomName);
if (atomId == IntPtr.Zero) {
throw new Exception("Impossible d'enregistrer l'atome du raccourci !");
}
if (!RegisterHotKey(this.Handle, atomId.ToInt32(), (int)modifiers, (int)key)) {
GlobalDeleteAtom(atomId);
throw new Exception("Impossible d'enregistrer le raccourci !");
}
this.hotkeys.Add(new HotKeyData(key, modifiers, atomId));
}
private void unregisterHotKey(HotKeyData hk) {
UnregisterHotKey(this.Handle, hk.AtomID.ToInt32());
GlobalDeleteAtom(hk.AtomID);
}
private void owner_HandleCreated(object sender, EventArgs e) {
this.AssignHandle(owner.Handle);
}
}
#region Classe HotKeyArgs
public class HotKeyArgs : EventArgs {
public HotKeyArgs(Keys key, HotKey.HotKeyModifiers modifiers) {
this.modifiers = modifiers;
this.key = key;
}
private Keys key;
public Keys Key {
get {return key;}
}
private HotKey.HotKeyModifiers modifiers;
public HotKey.HotKeyModifiers Modifiers {
get {return modifiers;}
}
}
#endregion
}
Historique
- 16 août 2005 09:57:12 :
- ajout remarque
- 23 août 2005 19:19:45 :
- Info MSDN
- 21 novembre 2005 14:28:48 :
- Ajout des mots clés
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
API? [ par BlackWizzard ]
en C, j'avait un prog du genre ::SetWindowPos(FindWindow("ConsoleWindowClass",NULL),HWND_TOP,0,0,0,0,SWP_SHOWWINDOW); (C pour chacher le console dos d
[C#] CopyTo => Pb de copy [ par adrien78 ]
J' ai absolument besoins de récréer la fonction CopyTo en C#=> Cependant j' ai deux pb : - Le fichier copié ne peut pas être lu (érreur de cop
System.Windows.Forms.MonthCalendar [ par Godzidane ]
Qlq'1 sait il comment récupérer, en C#, dans une WinForm, la date sélectionnée par un utilisateur dans le contrôle MonthCalendar ?Par avance merci.
Accès [ par fredza ]
Bonjour et bonne année à toutes et tous,J'ai un fichier ip.cs voilà brièvement son contenu :namespace iprog{ /// <summary> /// Description résum
Delete file c# [ par mustai ]
I try to delete file wich one i had created with System.IO.File.Copy(....), i always receive an exception like i dont have the right to delete it. Th
Ajouter dynamiquement des composants graphiques [ par Sebulba ]
Bonjourj'ai un thread qui doit créer un élément graphique sur la form pour pouvoir se représenter.mon problème est que je n'arrive pas à afficher une
System.Net.SocketPermission... [ par houseclubber ]
J'ai un problème. J'ai testé une source de ce site qui fait un client serveur multi telnet qui fonctionne chez moi, mais pas à mon école...Voici l'err
Afficher un byte : System.Byte[] [ par JohnEM13 ]
Bonjour,J'arrive pas a comprendre comment afficher la valeur d'une variable en byte.Par exemple :MessageBox.Show("Valeur : "+buf,"Test");Me donne Syst
Definition [ par GazGaz ]
lu voila je code en c# et en haut de chacune de mes pages il y a : ________________________________using System;using System.Collections;using System.
Hello World [ par Kazuya ]
Salut, j'ai un problem, je viends d'arriver dans le C# et j'arrive même pas a compiler Hello World, le compilo me sort une erreur: System.IO.TextWrite
|
Derniers Blogs
WORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBEWORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBE par JeremyJeanson
Depuis déjà un an, je conseille vivement les utilisateurs de Workflow Foundation 3 à migrer vers la version 4. L'information qui va suivre ne devrait donc pas trop prendre au dépourvu les personnes qui l'ont sagement suivi. Je profite de ce poste pour fai...
Cliquez pour lire la suite de l'article par JeremyJeanson TECHDAYS PARIS 2012 : NOUVELLES TENDANCES DU POSTE DE TRAVAIL - BRING YOUR OWN PCTECHDAYS PARIS 2012 : NOUVELLES TENDANCES DU POSTE DE TRAVAIL - BRING YOUR OWN PC par ROMELARD Fabrice
Speakers: Thierry Rapatout, Antoine Petit et Xavier Trebbia Cette session entre dans le cadre des RDV Décideurs des TechDays 2012, elle est liée à la consumérisation de l'IT et la mise en place du "DeskTop as a Service" dans de plus en ...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : SYSTEM CENTER SERVICE MANAGER 2012 VUE D'ENSEMBLETECHDAYS PARIS 2012 : SYSTEM CENTER SERVICE MANAGER 2012 VUE D'ENSEMBLE par ROMELARD Fabrice
Speakers: Julien Marechal, Gautier Confiant, Sébastien MEYER La session débute par le positionnement de la solution System Center par rapport aux concepts d'organisation ITIL. Le portail du catalogue de se...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : PLEINIèRE SECOND JOURTECHDAYS PARIS 2012 : PLEINIèRE SECOND JOUR par ROMELARD Fabrice
Après une première journée dédiée aux développeurs, cette seconde journée est dédiée au monde des entreprises et de ses applications. Ainsi, cette pleinière est dédiée à faire un 360 de l'évolution des applications Business aux demandes ac...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : RETOUR D'EXPéRIENCE SUR LA MISE EN PLACE D'UN CLOUD PRIVéTECHDAYS PARIS 2012 : RETOUR D'EXPéRIENCE SUR LA MISE EN PLACE D'UN CLOUD PRIVé par ROMELARD Fabrice
Speaker : Guillaume Rochette Cette session est dédiée à fournir le retour sur la mise en place d'un cloud privé (IaaS) par Osiatis pour son compte ou celui de ses clients. Ce projet s'est déroulé sur 4 mois et a permis de faire évoluer...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|