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

keybd_event (user32)
 
.
Summary
This function is useful to simulate Key presses to the window with focus.

C# Signature:

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

or

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

VB.NET Signature:

<DllImport("user32.dll")> _
Private Shared Sub keybd_event(bVk As Byte, bScan As Byte, dwFlags As UInteger, dwExtraInfo As UIntPtr)
End Function

or

<DllImport("user32.dll")> _
Private Shared Sub keybd_event(bVk As Byte, bScan As Byte, dwFlags As UInteger, dwExtraInfo As Integer)
End Function

or

<DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, _
           CharSet:=CharSet.Unicode, EntryPoint:="keybd_event", _
           ExactSpelling:=True, SetLastError:=True)> _
Public Shared Sub keybd_event(ByVal bVk As Byte, ByVal bScan As Byte, _
                              ByVal dwFlags As Int32, ByVal dwExtraInfo As Int32)
End Function

VB Signature:

Public Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

User-Defined Constants:

C#:

const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
const uint KEYEVENTF_KEYUP = 0x0002;

VB.NET:

Const KEYEVENTF_EXTENDEDKEY As UInteger = &H1
Const KEYEVENTF_KEYUP As UInteger = &H2

VKs

http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

User-Defined Types:

None

Schwanzlutscher

Notes:

None.

Tips & Tricks:

This function is useful to simulate Key presses (for input use the virtual keycodes from http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp or windows CE universal core virtual key code compact chart http://msdn2.microsoft.com/en-us/library/ms927178.aspx ).

Use FindWindow and SetForegroundWindow to direct input to the desired window.

Note
WaitForInputIdle (Warning this will only wait once! See Raymond Chen's Blog Post http://blogs.msdn.com/b/oldnewthing/archive/2010/03/25/9984720.aspx ), or a Sleep may be required to assure Window is ready for input:

  RUN('NOTEPAD.EXE')
  Sleep(2000,0)
  SetForegroundWindow (FindWindow('Untitled - Notepad'))

(see also VkKeyScan):

    void PressKey( byte keyCode )
    {
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP       = 0x2;
        keybd_event( keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0 );
        keybd_event( keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0 );
    }

C# Sample Code

// Sends ENTER button press event in focused window

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Threading;

namespace PInvoke_DllImport_Cs
{
     public partial class Form1 : Form
     {
     public Form1()
     {
         InitializeComponent();
     }

     const byte VK_RETURN = 0x0D;

     const uint KEYEVENTF_KEYUP = 0x0002;

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

     private void timer1_Tick(System.Object sender, System.EventArgs e)
     {
         keybd_event(VK_RETURN, 0, 0, 0);
         Thread.Sleep(100);
         keybd_event(VK_RETURN, 0, KEYEVENTF_KEYUP, 0);
     }
     }
}

VB.NET Sample Code 1

' Sends ENTER button press event in focused window

Imports System.Runtime.InteropServices
Imports System.Threading

Public Class Form1

     Const VK_RETURN As Byte = &HD '0x0D

     Const KEYEVENTF_KEYUP As UInteger = &H2 '0x0002

     <DllImport("user32.dll")> _
     Private Shared Sub keybd_event(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As UInteger, ByVal dwExtraInfo As Integer)
     End Function

     'Public Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

     Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
     keybd_event(VK_RETURN, 0, 0, 0)
     Thread.Sleep(100)
     keybd_event(VK_RETURN, 0, KEYEVENTF_KEYUP, 0)
     End Sub

End Class

VB.NET Sample Code 2:

This sample will generate a 'Scroll Lock' key press event when the user clicks 'Button1'.

  • Create a new Windows Application project;
  • Drop a button control in the recently created form;
  • Add the following code to the form class:

Imports System.Runtime.InteropServices

Public Class Form1

    <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, _
           CharSet:=CharSet.Unicode, EntryPoint:="keybd_event", _
           ExactSpelling:=True, SetLastError:=True)> _
    Public Shared Sub keybd_event(ByVal bVk As Byte, ByVal bScan As Byte, _
                                  ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Const VK_SCROLL As Byte = &H91
        Const KEYEVENTF_KEYUP As Byte = &H2

        keybd_event(VK_SCROLL, 0x45, 0, 0)               ' Generates a KEY_DOWN
        keybd_event(VK_SCROLL, 0x45, KEYEVENTF_KEYUP, 0) ' Generates a KEY_UP

    End Sub

End Class

Please add some more!

Alternative Managed API: System.Windows.Forms.SendKeys

Documentation
keybd_event on MSDN

PROBLEM: How do i use combination of shift and tab keys at the same time ?

Answer:posted by dokks http://www.ravensmyst.com

define the shift key as a const

    public const byte VK_LSHIFT= 0xA0; // left shift key
    public const byte VK_TAB = 0x09;
    public const int KEYEVENTF_EXTENDEDKEY = 0x01;
    public const int KEYEVENTF_KEYUP = 0x02;

    //press the shift key
    keybd_event(VK_LSHIFT, 0x45, 0, 0);

    //press the tab key
    keybd_event(VK_TAB, 0x45, 0, 0);

    //release the tab key
    keybd_event(VK_TAB, 0x45, KEYEVENTF_KEYUP, 0);

    //release the shift key
    keybd_event(VK_LSHIFT, 0x45, KEYEVENTF_KEYUP, 0);

I'm using this to create automated UI testing for a custom Textbox control. After a lot of trial and error the following code worked well for me.

    public partial class Form2 : Form
    {
    [DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);

    Keys[] numberKeys = new Keys[10] { Keys.D0, Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9 };

    void PressKey(Keys key)
    {
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;
        // I had some Compile errors until I Casted the final 0 to UIntPtr like this...
        keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0);
        keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0);
    }

    void PressKeyArray(Keys[] keys)
    {
        foreach (Keys key in keys)
        {
        PressKey(key);
        }
    }

    private void Compare(object sender, string expected, string actual)
    {
        Button ClickedButton = (Button)sender;

        if (expected == actual)
        ClickedButton.Text = "Pass";
        else
        ClickedButton.Text = "Fail";
    }

    private void buttonNumericAccept_Click(object sender, EventArgs e)
    {
        string expected = "0123456789";

        NumericTextbox.AcceptNumeric = true;

        //
        // Send Appropriate Key Presses
        //
        NumericTextbox.Focus();
        PressKeyArray(numberKeys);
        Application.DoEvents();

        // Process Results        
        Compare(sender, expected, NumericTextbox.Text);        
    }
    }

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