With WPF, you can checkup
System.Windows.Input.Keyboard.IsKeyToggled(Key.Insert)
, see
http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.iskeytoggled.aspx[
^].
Unfortunately, there is no such thing in
System.Windows.Forms
. One work-around is using Windows API
GetKeyState
, via P/Invoke, see
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646301%28v=vs.85%29.aspx[
^]. For toggled state you need to examine low-order bit of the result, so mask it like this result = GetKeyState(/*...*/) & 1.
Unfortunately, using P/Invoke would break platform compatibility — the code will work only on Windows (a Forms application could work well on many platforms without recompilation under Mono,
http://en.wikipedia.org/wiki/Mono_%28software%29[
^],
http://www.mono-project.com/[
^]). By this reason, your approach which does not require P/Invoke is better.
There is one more reason: every instance of
System.Windows.Forms.RichTextBox
control has its own insert state that is independent of the global insert state as well as the insert state of all other
RichTextBox
controls. Take a look at this text:
http://vb.mvps.org/hardcore/html/controllingrichtextboxinsertstate.htm[
^] (sorry, it's in VB.NET, but you can understand it). See also this discussion:
http://www.codeguru.com/forum/showthread.php?t=276369[
^].
You are right about unnecessary duplication of a functionality, but this functionality is not expose, which is a shame, I would say. So, you will need to handle some key event anyway, because even when you can poll the keyboard status, you need some event to trigger your check.
—SA