How to simulate pressing a multimedia key (in C)?

Modern keyboards have special multimedia keys, for example. Pause / Play or Open Web Browser. Is it possible to write a program that “presses” these keys?

I would prefer a solution in C, but I would also make a language agnostic decision.

+3
source share
2 answers

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

You need to build INPUT structures by setting the type member to INPUT_KEYBOARD. In the ki member (type KEYBDINPUT) you can set vk (virtual key) in the 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 have not tested the following, but should look 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));
+7
source

Even simpler than the accepted keybd_event answer . No structures, just a call with numerical 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);
+4
source

Source: https://habr.com/ru/post/1748405/


All Articles