Posted by: techsavygal | March 2, 2009

Lock keys on a form or application!

Hi,

Recently, i had a request from one of my friends who is developing a game on how to lock out special keys such as Alt+Tab, Ctrl+Esc,etc. on a windows application. Interested in that request, i went on looking on how to acheive this and got the information from msdn and codeproject website.

The following will lock out special keys on windows form .

#region KeyBoard Hook Structure

// Structure returned by the hook whenever a key is pressed

public struct KBDLLHOOKSTRUCT

{

public int vkCode;

public int scanCode;

public int flags;

public int time;

public int dwExtraInfo;

}

#endregion

#region Constructors

/// <summary>

/// Sets up a keyboard hook to trap all keystrokes without

/// passing any to other applications.

/// </summary>

public KeyboardHook()

{

proc = new LowLevelKeyboardProcDelegate(HookCallback);

using (Process curProcess = Process.GetCurrentProcess())

using (ProcessModule curModule = curProcess.MainModule)

{

hookID = SetWindowsHookEx(WH_KEYBOARD_LL, proc,

GetModuleHandle(curModule.ModuleName), 0);

}

}

/// <summary>

/// Sets up a keyboard hook with custom parameters.

/// </summary>

/// <param name=”param”>A valid name from the Parameter enum; otherwise, the

/// default parameter Parameter.None will be used.</param>

public KeyboardHook(string param)

: this()

{

if (!String.IsNullOrEmpty(param) && Enum.IsDefined(typeof(Parameters), param))

{

SetParameters((Parameters)Enum.Parse(typeof(Parameters), param));

}

}

/// <summary>

/// Sets up a keyboard hook with custom parameters.

/// </summary>

/// <param name=”param”>A value from the Parameters enum.</param>

public KeyboardHook(Parameters param)

: this()

{

SetParameters(param);

}

private void SetParameters(Parameters param)

{

switch (param)

{

case Parameters.None:

break;

case Parameters.PassAllKeysToNextApp:

PassAllKeysToNextApp = true;

break;

}

}

#endregion

#region Check Modifier keys

/// <summary>

/// Checks whether Alt, Shift, Control or CapsLock

/// is enabled at the same time as another key.

/// Modify the relevant sections and return type

/// depending on what you want to do with modifier keys.

/// </summary>

private void CheckModifiers()

{

StringBuilder sb = new StringBuilder();

if ((GetKeyState(VK_CAPITAL) & 0x0001) != 0)

{

//CAPSLOCK is ON

sb.AppendLine(“Capslock is enabled.”);

}

if ((GetKeyState(VK_SHIFT) & 0x8000) != 0)

{

//SHIFT is pressed

sb.AppendLine(“Shift is pressed.”);

}

if ((GetKeyState(VK_CONTROL) & 0x8000) != 0)

{

//CONTROL is pressed

sb.AppendLine(“Control is pressed.”);

}

if ((GetKeyState(VK_MENU) & 0x8000) != 0)

{

//ALT is pressed

sb.AppendLine(“Alt is pressed.”);

}

Console.WriteLine(sb.ToString());

}

#endregion Check Modifier keys

#region Hook Callback Method

/// <summary>

/// Processes the key event captured by the hook.

/// </summary>

private int HookCallback(

int nCode, int wParam, ref KBDLLHOOKSTRUCT lParam)

{

bool blnEat = PassAllKeysToNextApp;

switch (wParam)

{

case 256:

case 257:

case 260:

case 261: // Alt+Tab, Alt+Esc, Ctrl+Esc, Left Windows key, Right Windows key

blnEat = ((lParam.vkCode == 0x09) && (lParam.flags == 0x20)) || ((lParam.vkCode == 0x1B) && (lParam.flags == 0x20)) || ((lParam.vkCode == 0x1B) && (lParam.flags == 0x00)) || ((lParam.vkCode == 0x5B) && (lParam.flags == 0x01)) || ((lParam.vkCode == 0x5C) && (lParam.flags == 0x01));

break;

}

OnKeyIntercepted(new KeyboardHookEventArgs(lParam.vkCode, blnEat));

//If this key is being suppressed, return a dummy value

if (blnEat == true)

{

return 1;

}

else

{

return CallNextHookEx(hookID, nCode, wParam, ref lParam);

}

}

#endregion

#region Event Handling

/// <summary>

/// Raises the KeyIntercepted event.

/// </summary>

/// <param name=”e”>An instance of KeyboardHookEventArgs</param>

public void OnKeyIntercepted(KeyboardHookEventArgs e)

{

if (KeyIntercepted != null)

KeyIntercepted(e);

}

/// <summary>

/// Delegate for KeyboardHook event handling.

/// </summary>

/// <param name=”e”>An instance of InterceptKeysEventArgs.</param>

public delegate void KeyboardHookEventHandler(KeyboardHookEventArgs e);

/// <summary>

/// Event arguments for the KeyboardHook class’s KeyIntercepted event.

/// </summary>

public class KeyboardHookEventArgs : System.EventArgs

{

private string keyName;

private int keyCode;

private bool passThrough;

/// <summary>

/// The name of the key that was pressed.

/// </summary>

public string KeyName

{

get { return keyName; }

}

/// <summary>

/// The virtual key code of the key that was pressed.

/// </summary>

public int KeyCode

{

get { return keyCode; }

}

/// <summary>

/// True if this key combination was passed to other applications,

/// false if it was trapped.

/// </summary>

public bool PassThrough

{

get { return passThrough; }

}

public KeyboardHookEventArgs(int evtKeyCode, bool evtPassThrough)

{

keyName = ((Keys)evtKeyCode).ToString();

keyCode = evtKeyCode;

passThrough = evtPassThrough;

}

}

#endregion

Ta!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: