Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

GetKeyState (user32)
 
.
Summary
The GetKeyState function retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed).

C# Signature:

[DllImport("user32.dll")]
static extern short GetKeyState(int nVirtKey);

User-Defined Types:

VK

Notes:

Here are some sample values for nVirtKey:

const int VK_SHIFT = 0x10;
const int VK_CONTROL = 0x11;
const int VK_MENU = 0x12;

Tips & Tricks:

The Enum Keys in System.Windows.Forms has the key code used for this function, so you don't need to define const

Sample Code:

This Sample use this API to create a new textbox to support overwrite mode, testing the state of insert key.

Imports System.Windows.Forms

Public Class MinhaNovaTextbox

  Inherits System.Windows.Forms.TextBox

  Dim bInserting As Boolean = True

  Private Declare Function GetKeyState _
      Lib "user32" (ByVal nVirtKey As Long) As Integer

  Public Sub New()
    MyBase.New()
    bInserting = GetKeyState(Keys.Insert)
  End Sub

  Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
    bInserting = GetKeyState(Keys.Insert)
    If Not bInserting Then
      Me.SelectionLength = 1
    End If
    MyBase.OnKeyPress(e)
  End Sub

End Class

Alternative Managed API:

Do you know one? Please contribute it!

Documentation
GetKeyState on MSDN

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Find References
Show Printable Version
Revisions