I have a form with a rich text box control. Is there a way to have caps lock turn on whenever the rich textbox control has focus? And turn it off if the rich text box loses focus? I am using C#
I would suggest instead capturing the key input and replacing it with the associated uppercase version. Otherwise, imagine a situation where the user clicks in the textbox, switches to another app, realizes Caps Lock is on, throws a brick at their computer out of frustration and then switches back to your app where the cursor is sitting in a textbox expecting uppercase letters but Caps Lock is now off.
Well there are a number of ways to look at this, if you want client-side capitalization then something like the Jquery capitalizer would automatically convert text into uppercase during typing if hooked into, say, the keyup event.
Or if you wanted server side capitalization then you could use C# to String.ToUpper() method in a round-trip.
I don't think that turning caps lock on is the best solution.. you might be better off subscribing to events like textchanged and converting the input to upper case.
This should cover the case that something was pasted into the box as well..
You can't do it even with using the Win32 API.
The following code will tell you if the CAPS LOCK is On but the API does not have an equivalent SetKeyState function
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true, CallingConvention=CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode);
public void getCapsLockState() {
bool CapsLock = (((ushort) GetKeyState(0x14 /*VK_CAPITAL*/)) & 0xffff) != 0;
}
I would use the KeyUp event, get the last character in .Text and use ToUpper(). Simple and efficient.
This scenario is usually solved by capturing one of the key events and changing the data. Toggling the CAPS LOCK key isn't optimal because many users would still be using SHIFT (automatically) which would give you lower case letters. Also, it might feel weird to some users (e.g. me). I would suggest KeyPress rather than KeyUp as Ed.C suggested, as it gives you the actual character right there in the event:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
richTextBox1.KeyPress += new KeyPressEventHandler(richTextBox1_KeyPress);
}
void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = Char.ToUpper(e.KeyChar);
}
}