CSharp .Net Tutorial: Toggling Keyboard Functions

James Cloud
Introduction

In the steps given below, you will learn how to toggle the caps-lock, scroll-lock, and numlock on the keyboard using CSharp .Net code. This tutorial is useful for macro utilities, keyboard utilities, etc. Not only will you learn how to simulate the fore-mentioned keys, but you will learn how to create a function that will reliably allow you to press any Keys.Key through code.

Step One - Windows API Declarations

The function to simulate key on the key can be accessed through Window's API. However, in order to make use of the Window's API you must use the 'System.Runtime.InteropServices' framework like so,

using System.Runtime.InteropServices;

With the Window's API now accessible, add this code to your classes object declaration area,

[DllImport("user32.dll")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

This will import the 'keyb_event' function from the user32.dll which will be used in creating a custom made keyboard key simulation function below in step two.

Step Two - Creating a Custom Sendkeys Function

There is a basic function that comes with the .Net framework called, 'SendKeys'. However, this function can be considered less than reliable and should not be used regularly. So, create a void called, 'SendKey' using the source code supplied here,

public void SendKey(Keys Key, bool Release, bool Resume)
{

if (!Resume)
{
keybd_event(Convert.ToByte(Key), 0, 0, 0);

if(Release)
keybd_event(Convert.ToByte(Key), 0, 0x02, 0);
}
else
{
keybd_event(Convert.ToByte(Key), 0, 0x02, 0);
}
}

This newly created 'SendKey' method will serve as a working replacement for the .Net Framework's SendKeys() function. Besides from simulating the caps-lock, scroll-lock, and numlock keys it allows the simulation of any key under the Keys.Key enumerator.

Conclusion

Now, with a reliable key simulation function, you can now easy toggle the caps-lock, scroll-lock, and numlock keys. Here is how do toggle each of these keys,

// Toggle Caps-lock
SendKey(Keys.Capital, true, false);

// Toggle Scroll-Lock
SendKey(Keys.Scroll, true, false);

// Toggle Numlock
SendKey(Keys.NumLock, true, false);

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.