samuri25404 Grandmaster Cheater Reputation: 7
Joined: 04 May 2007 Posts: 955 Location: Why do you care?
|
Posted: Thu Jan 31, 2008 8:49 pm Post subject: [C#] User Customizable Hotkeys with a Hook |
|
|
This post is going to discuss how to use the keyboard hook that I created with user-customizable hotkeys.
First you'll need my keyboard hook class (go get it from the other post if you don't have it already).
Next, we're going to create an interface, for incredible simplicity:
Code: |
public interface IKeyFunction
{
string classname
{
get;
}
Hook.VK key
{
get;
set;
}
void Operation();
}
|
If you don't know about interfaces, I suggest you Google.
Now, we should define some classes that inherit from this interface. I'll show an example:
Code: |
public class Godmode : IKeyFunction
{
public string classname
{ get { return "Godmode"; } }
private Hook.VK _key; //we use this to prevent an infinite loop
public Hook.VK key
{
get { return _key; }
set { _key = value; }
}
public void Operation()
{
}
}
|
And you would simply put whatever it's supposed to do in the Operation() method. (Forget about the "classname" property for now)
~~
After defining all the classes that you want, create this:
Code: |
public static List<IKeyFunction> keyfunctions = new List<IKeyFunction>(
new IKeyFunction[] {
new Godmode(),
});
|
And here, I'm just using the Godmode class as an example. Replace the "Godmode" with whatever your classes name is. Then, simply create as many of those as you need.
~~
Now that we've got all of our events set up, we need to create our KeyHandler() method.
Start off with the bare backbone:
Code: |
public static void KeyHandler(
IntPtr wParam,
IntPtr lParam)
{
}
|
Then, add this code into it:
Code: |
//first get the key that we need
int key = System.Runtime.InteropServices.Marshal.ReadInt32(lParam);
Hook.VK vk = (Hook.VK)key;
|
This is nothing new--simply getting the key.
However, here's where the new stuff comes in:
Code: |
//loop through all of the classes to find a match on the hotkey
IKeyFunction kf = null;
foreach (IKeyFunction keyfunction in keyfunctions)
{
if (keyfunction.key == vk)
{
kf = keyfunction;
break;
}
}
if (kf == null) //there was no match, so we don't need to do anything
return;
kf.Operation();
|
~~
Now, for editing the hotkeys of the little classes...
Remember that little "classname" property that we had in the interface?
Code: |
public static void RegisterHotkey(
string sClass,
Hook.VK key)
{
IKeyFunction kf = null, temp;
foreach (IKeyFunction keyfunction in keyfunctions)
{
if (keyfunction.classname == sClass)
{
kf = keyfunction;
break;
}
}
if (kf == null) return;
temp = kf;
//now we've got the keyfunction
//set our property
kf.key = key;
//reupdate the list:
//first clear away the old class
keyfunctions.Remove(temp);
//now add the new one
keyfunctions.Add(kf);
}
|
I've commented it enough that you should understand it, but if you don't, my Inbox is always open.
Have fun!
_________________
|
|