begin process at 2010 02 10 12:50:16
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

API

 > CRÉEZ VOS PROPRES RACCOURCIS CLAVIER AU NIVEAU SYSTÈME

CRÉEZ VOS PROPRES RACCOURCIS CLAVIER AU NIVEAU SYSTÈME


 Information sur la source

Note :
10 / 10 - par 5 personnes
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :API Source .NET ( DotNet ) Classé sous :raccourci, system, registerhotkey, globaladdatom, wmhotkey Niveau :Initié Date de création :11/08/2005 Date de mise à jour :21/11/2005 14:28:48 Vu / téléchargé :20 728 / 947

Auteur : sebmafate

Ecrire un message privé
Site perso
Ce membre participe au partage de revenus publicitaires
Commentaire sur cette source (14)
Ajouter un commentaire et/ou une note


 Description

Cliquez pour voir la capture en taille normale
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
}


 Fichier Zip

Les Membres Club peuvent télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip


 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

Source avec Zip Source .NET (Dotnet) SILVERLIGHT : METTEZ UNE TOUCHE D'AOP DANS VOS CONTRÔLES
Source avec Zip Source avec une capture Source .NET (Dotnet) BATCHIMAGECONVERTER
Source avec Zip Source .NET (Dotnet) MAFBINDERHELPER : UNE CLASSE POUR BINDER AUTOMATIQUEMENT VOS...
Source avec Zip Source .NET (Dotnet) WINDOWS FORMS VALIDATORS
Source avec Zip Source avec une capture Source .NET (Dotnet) BLUREDLABEL : UN LABEL AVEC UN FOND TROUBLE, COMME SOUS VIST...

 Sources de la même categorie

Source avec Zip Source avec une capture Source .NET (Dotnet) UTILISATION DE L'API VIRTUAL DISK IMAGE DE WINDOWS 7 par Willi
Source avec Zip Source .NET (Dotnet) CHESS GAME CORE - LIBRAIRIE JEU D'ÉCHEC EN C# par Bidou
Source .NET (Dotnet) CHANGER LA RESOLUTION DE VOTRE ECRAN, UTILISATION DES API WI... par mechtaly
Source avec Zip Source .NET (Dotnet) CRÉER SON PROPRE DESIGNER COMME CELUI DE VISUAL STUDIO par ShareVB
Source avec Zip Source .NET (Dotnet) CSVSHARP. DLL D'IMPORT/EXPORT DE CONTENU AU FORMAT CSV par heriquet

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture Source .NET (Dotnet) LINKY : GESTIONNAIRE DE ROOTS par xmox667
Source avec Zip Source .NET (Dotnet) JOUER AVEC VOS SHORTCUTS (AJOUT, SUPPRESSION, MODIFICATIONS) par zebobo5
Source .NET (Dotnet) OBTENIR LE NOM DETAILLE DU SYSTEME D'EXPLOITATION par Xya
Source avec Zip Source .NET (Dotnet) HOOK GLOBAL (SYSTEM-WIDE HOOK) - BLOCAGE DE TOUCHES par coq
Source avec Zip Source .NET (Dotnet) CRÉER UN RACCOURCIS EN C# par Cameleon69

Commentaires et avis

Commentaire de sebmafate le 11/08/2005 16:12:48 administrateur CS

pas cool... j'ai oublié de mettre les commentaires... je m'en charge ce soir ;)

Commentaire de Lutinore le 11/08/2005 21:13:01 administrateur CS

Utiliser les hot keys c'est mieux qu'un hook clavier !?

Commentaire de sebmafate le 11/08/2005 21:17:06 administrateur CS

bien mieux oui ;)

Commentaire de coq le 11/08/2005 21:17:06 administrateur CS

Ca evite de devoir mettre un hook en place, donc rien que pour ça oui, c'est mieux :p

Commentaire de Lutinore le 11/08/2005 21:54:15 administrateur CS

D'accord merci.

Commentaire de sebmafate le 11/08/2005 22:23:54 administrateur CS

en fait, le principe est simple... tu enregistres un raccourci clavier dans le système, et lorsqu'il est déclenché, Windows t'en informe...

Commentaire de iow4 le 24/06/2006 22:12:42

Superbe source
merci

Commentaire de Gamer_man le 25/09/2006 02:02:23

Bonsoir !

Une petite question bien que je n'ai pas trop cherché, peut on consulter quelque part, et si possible me dire où, une documentation concernant les fonctions disponibles dans "user32.dll" !

Merci bien !

Bisous

Commentaire de coq le 25/09/2006 19:27:32 administrateur CS

Salut,

Une liste complète doit sans doute exister quelquepart mais en attendant une solution simple est d'utiliser dumpbin pour avoir la liste des méthodes exportées puis de les chercher dans la MSDN (http://msdn.microsoft.com/library/).

dumpbin %windir%\system32\user32.dll /EXPORTS /OUT:user32.dll.txt

Commentaire de Gamer_man le 10/10/2006 02:28:07

Bonsoir !

J'aurais besoin encore d'un petit éclairage...

Qu'est ce qu'un atome ?
D'après ce que je pourrais en comprendre, je dirais que c'est une chaine identifiant unique... mais où pourrais je trouver quelque détails sur le principe ?

Merci,

Bisous

Commentaire de vinz7tim le 20/10/2006 14:24:20

Trés bon travail !

Commentaire de mechtaly le 09/03/2008 22:24:09 10/10

juste une question svp;
peut on desactiver Ctrl-alt-sup avec le hook  clavier?

Commentaire de BruNews le 09/03/2008 23:38:54 administrateur CS

Absolument NON, Ctrl-alt-sup a subi un RegisterHotKey AVANT l'ouverture de session. L'unique voie fiable d'interception est un filter driver sur le clavier.

Question plus ancienne, hook mieux que hot key:
ça n'a aucun rapport, les buts sont différents. Hot key est un moyen de notification, le hook est un moyen d'interception en plus de la notification.

Commentaire de MoKaLux le 22/10/2009 02:08:48

Salut à vous,

encore mille mercis à vous tous pour vos projets que vous daignez partager au monde (www).

J'ai donc utilisé un projet afin de faire des hotkeys pour controler la souris. Je comprends pour qu'un hotkey soit un hotkey il faut un modifier (CTRL, ALT, WIN, SHIFT).

Mon problème est qu'en utilisant les modifiers cela altère le comportement de mon click de souris.

Par exemple si je vais sur une page web et que je clique n'importe où sur la page alors le clique sur la page va me selectionner le texte du haut de la page jusqu'à mon curseur (si j'ai défini le modifier en tant que SHIFT). Si je choisis CTRL comme modifier alors j'ai encore un autre truc, idem avec ALT..., donc tous les modifers altère le clique de la souris.

Donc comment faire pour éviter cela SVP ???

Merci pour vos éclaircicements...

 Ajouter un commentaire


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#=&gt; 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{ /// &lt;summary&gt; /// 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


Nos sponsors


Sondage...

CalendriCode

Février 2010
LMMJVSD
1234567
891011121314
15161718192021
22232425262728

Consulter la suite du CalendriCode

 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,842 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales