开发者

How to simulate multimedia key press (in C)?

Modern keyboards have special multimedia keys, e.g. 'Pause/Play' or 'O开发者_如何学JAVApen Web Browser'. Is it possible to write a program that "presses" these keys?

I would prefer solution in C, but I would accept a language agnostic solution, too.


Use the SendInput Windows API, if you are talking about programming under Win32.

You need to build INPUT structures, setting the type member to INPUT_KEYBOARD. In the ki member (KEYBDINPUT type), you can set vk (virtual key) to your desired VK code (for example, VK_MEDIA_NEXT_TRACK, VK_MEDIA_STOP).

Virtual key codes: http://msdn.microsoft.com/en-us/library/dd375731(v=VS.85).aspx

SendInput Function: http://msdn.microsoft.com/en-us/library/ms646310(v=VS.85).aspx

I've not tested the following, but should be like this:

KEYBDINPUT kbi;
kbi.wVk = VK_MEDIA_STOP; // Provide your own
kbi.wScan = 0;
kbi.dwFlags = 0;  // See docs for flags (mm keys may need Extended key flag)
kbi.time = 0;
kbi.dwExtraInfo = (ULONG_PTR) GetMessageExtraInfo();

INPUT input;
input.type = INPUT_KEYBOARD;
input.ki   = kbi;

SendInput(1, &input, sizeof(INPUT));


Even more easier than the accepted answer is keybd_event. No structs just a call with numeric parameters.

// C# example:
public const int KEYEVENTF_EXTENDEDKEY = 1;
public const int KEYEVENTF_KEYUP = 2;
public const int VK_MEDIA_NEXT_TRACK = 0xB0;
public const int VK_MEDIA_PLAY_PAUSE = 0xB3;
public const int VK_MEDIA_PREV_TRACK = 0xB1;

[DllImport("user32.dll", SetLastError = true)]
public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo);

keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENDEDKEY, IntPtr.Zero);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜