Keybd event to windows

Функция keybd_event

Функция keybd_event синтезирует нажатие клавиши. Система может использовать такое синтезируемое нажатие клавиши, чтобы создать сообщение WM_KEYUP или WM_KEYDOWN. Вызывает функцию keybd_event программа обработки прерываний драйвера клавиатуры.

Windows NT/2000/XP: Эта функция была заменена. Используйте SendInput вместо нее.

[in] Определяет код виртуальной клавиши. Код должен быть значением в диапазоне от 1 до 254. Полный список см. в статье Коды виртуальных клавиш.

Этот параметр не используется.

[in] Определяет различные виды операций функции. Этот параметр может состоять из одного или нескольких ниже следующих значений.

Предназначение

KEYEVENTF_EXTENDEDKEY

Если он установлен, скэн-коду предшествует префиксный байт, имеющий значение 0xE0 (224).

KEYEVENTF_KEYUP

Если он установлен, клавиша была отпущена. Если не установлен, клавиша была нажата.

[in] Определяет дополнительное значение, связанное с нажатием клавиши.

У этой функции нет возвращаемых значений.

Прикладная программа может смоделировать нажатие клавиши PrintScreen , чтобы получить снимок экрана и сохранить его в буфере обмена. Чтобы сделать это, вызовите keybd_event с установленным параметром bVk в VK_SNAPSHOT .

Windows NT/2000/XP: Функция keybd_event может переключить клавиши NUM LOCK, CAPS LOCK и SCROLL LOCK.

Windows 95/98/Me: Функция keybd_event может переключить только клавиши CAPS LOCK и SCROLL LOCK. Она не может переключить клавишу NUM LOCK.

Ниже следующее типовая программа переключает индикатор NUM LOCK, используя функцию keybd_event () виртуальной клавишей VK_NUMLOCK . Требуется Булево значение, которое указывает, должен ли индикатор быть выключен — (ЛОЖЬ (FALSE)) или включен — (ИСТИНА (TRUE)). Та же самая методика может использоваться для клавиши CAPS LOCK ( VK_CAPITAL ) и клавиши SCROLL LOCK ( VK_SCROLL ).

void SetNumLock( BOOL bState )

keybd_event (Windows CE 5.0)

This function synthesizes a keystroke. The system can use such a synthesized keystroke to generate a WM_KEYUP or WM_KEYDOWN message.

Parameters

  • bVk
    [in] Specifies a virtual-key code. The code must be a value in the range 1 to 254. For a list of virtual-key codes, see Virtual-Key Codes.
  • bScan
    [in] Specifies a hardware scan code for the key.
  • dwFlags
    [in] Specifies various aspects of function operation. An application can use any combination of the following predefined constant values to set the flags.
    Value Description
    KEYEVENTF_EXTENDEDKEY If specified, the scan code will be treated as an extended key by giving it a prefix byte having the value 0xE0 (224).
    KEYEVENTF_KEYUP If specified, the key is being released. If not specified, the key is being pressed.
    KEYEVENTF_SILENT If specified, a keystroke is simulated, but no clicking sound is made.
  • dwExtraInfo
    [in] Specifies an additional 32-bit value associated with the keystroke.

Return Values

Remarks

When keyboard input is disabled with EnableHardwareKeyboard(FALSE), you can simulate keyboard input using keybd_event.

Although keybd_event passes an OEM-dependent hardware scan code to the system, applications should not use the scan code. The system converts scan codes to virtual-key codes internally and clears the up/down bit in the scan code before passing it to applications.

The parameters bVk and bScan are treated independently. The OS does not use bVk to generate bScan and does not use bScan to generate bVk.

An application can simulate a press of the PRINTSCREEN key in order to obtain a screen snapshot and save it to the clipboard. To do this, call keybd_event with the bVk parameter set to VK_SNAPSHOT, and the bScan parameter set to 0 for a snapshot of the full screen or set bScan to 1 for a snapshot of the active window.

keybd_event function (winuser.h)

Synthesizes a keystroke. The system can use such a synthesized keystroke to generate a WM_KEYUP or WM_KEYDOWN message. The keyboard driver’s interrupt handler calls the keybd_event function.

Syntax

Parameters

A virtual-key code. The code must be a value in the range 1 to 254. For a complete list, see Virtual Key Codes.

A hardware scan code for the key.

Controls various aspects of function operation. This parameter can be one or more of the following values.

Value Meaning
KEYEVENTF_EXTENDEDKEY 0x0001 If specified, the scan code was preceded by a prefix byte having the value 0xE0 (224).
KEYEVENTF_KEYUP 0x0002 If specified, the key is being released. If not specified, the key is being depressed.

An additional value associated with the key stroke.

Return value

Remarks

An application can simulate a press of the PRINTSCRN key in order to obtain a screen snapshot and save it to the clipboard. To do this, call keybd_event with the bVk parameter set to VK_SNAPSHOT.

Examples

The following sample program toggles the NUM LOCK light by using keybd_event with a virtual key of VK_NUMLOCK. It takes a Boolean value that indicates whether the light should be turned off (FALSE) or on (TRUE). The same technique can be used for the CAPS LOCK key (VK_CAPITAL) and the SCROLL LOCK key (VK_SCROLL).

Keybd event to windows

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I am using keybd_event to simulate keyboard in applications. Function works perfect in notepad, calc, all windows, etc. but in some directx program it is getting error. On some computers it can type keys but on some others it can not. I have no idea what to do to fixt it or what is missing on those computers.

Anyone has ever met this problem or know how to fix it please ?

Btw that’s a part of source

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

private void keybd_press(byte bVk)
<
keybd_event(bVk, 0, 0, new System.IntPtr());
keybd_event(bVk, 0, KEYEVENTF_KEYUP, new System.IntPtr());
>

Answers

Hi Quirm, in my own experiences in this area I found that just sending the wm_keydown and wm_keyup events was more reliable with DirectX applications. Here is some of the interop code:

public void SendKey( ushort key, IntPtr hWnd)

SendMessage(hWnd, WM_KEYDOWN, key, 0);

SendMessage(hWnd, WM_KEYUP, key, 0);

[ DllImport ( «user32.dll» )] //Set the active window

public static extern IntPtr SetActiveWindow( IntPtr hWnd);

[ DllImport ( «user32.dll» )] //sends a windows message to the specified window

public static extern int SendMessage( IntPtr hWnd, int Msg, uint wParam, int lParam);

public const ushort WM_KEYDOWN = 0x0100;

public const ushort WM_KEYUP = 0x0101;

Hope that helps,

All replies

Hi Quirm, in my own experiences in this area I found that just sending the wm_keydown and wm_keyup events was more reliable with DirectX applications. Here is some of the interop code:

public void SendKey( ushort key, IntPtr hWnd)

SendMessage(hWnd, WM_KEYDOWN, key, 0);

SendMessage(hWnd, WM_KEYUP, key, 0);

[ DllImport ( «user32.dll» )] //Set the active window

public static extern IntPtr SetActiveWindow( IntPtr hWnd);

[ DllImport ( «user32.dll» )] //sends a windows message to the specified window

public static extern int SendMessage( IntPtr hWnd, int Msg, uint wParam, int lParam);

public const ushort WM_KEYDOWN = 0x0100;

public const ushort WM_KEYUP = 0x0101;

Hope that helps,

Dennis — Is there any particular reason you didn’t use PostMessage? I’m looking at the documentation for the two functions and am not seeing why a person would choose one over the other. Just wondering.

Also, is the key parameter (passed to SendMessage in SendKey()) sill the virtual-key code for a given key? This was the case for keybd_event. Again, the documentation for SendMessage isn’t really clear on this issue as far as I can tell.

(Perhaps I should find better documentation!)

I did all of this quite a while ago but yeah I think that’s why I chose Send over Post in this case. I probably tried it both ways and found Send to be more reliable for what I was doing.

Yes the ushort param is the virtual key code for the key.

IT not work when the window is IE

im a newbie too, but read this msdn information. http://msdn.microsoft.com/en-us/library/windows/desktop/ms646304(v=vs.85).aspx

keybd_event takes 4 parameters.
this is my own code to write a keyboard event A after 5 seconds.

int main()
< Sleep(5000);
keybd_event(0x41,0x41,0,0);
keybd_event(0x41,0x41,KEYEVENTF_KEYUP,0);
return 0;
>

the first parameter is the code/virtual code for the button you want, the 2nd one is the hardware scan, i found some example elsewhere(a not working example, but i got a hint), it should be the hex code for the character/key you want. Fill with the hex from this site: http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
the third can be 0x01, 0x02 /KEYEVENTF_KEYUP, or 0 for the not those 2 value, and the last parameter is additional info, which i put 0 cause idk wat it does.
seems to work for notepad
im going to use in some directx app though, and i saw this thread about not being able to work in some dx apps, so im a bit worried cause im a newbie.

anyway, try not using 0 in your code for the 2nd parameter.
keybd_event(bVk, 0, 0, new System.IntPtr());
keybd_event(bVk, 0, KEYEVENTF_KEYUP, new System.IntPtr());
change them to

get the hex value of bVk, hbvk ?
keybd_event(bVk, hbVk, 0, new System.IntPtr());
keybd_event(bVk, hbVk , KEYEVENTF_KEYUP, new System.IntPtr());
wonder if that will fix or rig anything.

I can’t believe that this works for you

SendMessage with either WM_KEYDOWN or WM_KEYUP NEVER I tell you, but NEVER works for me! NEVER.

No matter what I have done, what I have tried, EVEN ONCE IN MY LIFE I did NOT succeed with it EVEN ONCE IN MY LIFE.

But keybd_event on the other hand, worked for me much better, even great!

I think the reason that SendMessage with either WM_KEYDOWN or WM_KEYUP works for Quirm and for me not, is that some settings in our computers, or our windows, or our operating systems are different. SO please someone tell me what can I do, NOT in C++, and NOT in C#, but in my computer, what can I do to make this function to work for me too. Believe me I put exactly the same correct parameters as Dennis Stone suggested. Quirm was satisfied, but me no.

Don’t think that I haven’t tried PostMessage function with either WM_KEYDOWN or WM_KEYUP too, because I have tried, and PostMessage is exactly the same as SendMessage for me too.

NEVER works! NEVER!

Just a waste to write it in my code. Useless, idle, does nothing like comment effect!

I just called GetLastError() function and printed the return value.

The console showed the integer 5, and MSDN says that this means «Acess is denied», and this is the reason that the SendMessage function with either WM_KEYDOWN or WM_KEYUP doesn’t work for me, but I do NOT understand WHY access is denied. Please explain me!

Weird! I get the same error code (5 that msdn says «Access is denied») with keybd_event function too, but it still working unlike either SendMessage or PostMessage function with either WM_KEYDOWN or WM_KEYUP. This is not clear to me too. Please explain me this too!

Читайте также:  Кодеки для arw windows 10
Оцените статью