Send multimedia commands

后端 未结 3 1852
春和景丽
春和景丽 2021-01-20 17:38

Is there some way that I can send multimedia control commands like next song, pause, play, vol up, etc. to the operating system? Commands that are sent when pressing Fn

3条回答
  •  逝去的感伤
    2021-01-20 17:52

    Actually, the answer of dxramax gives me erratic behavior. I'm posting this answer that gives me consistent behavior, and also has some more details.

    To send multimedia keys, including Play/Pause, NextTrack, PrevTrack, etc, you can use keybd_event:

    public class Program
    {
        public const int KEYEVENTF_EXTENTEDKEY = 1;
        public const int KEYEVENTF_KEYUP = 0;
        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")]
        public static extern void keybd_event(byte virtualKey, byte scanCode, uint flags, IntPtr extraInfo);
    
        public static void Main(string[] args)
        {
            keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);    // Play/Pause
    
            //keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);  // PrevTrack
            //keybd_event(VK_MEDIA_NEXT_TRACK, 0, KEYEVENTF_EXTENTEDKEY, IntPtr.Zero);  // NextTrack
        }
    

    Here is a list to the supported key codes that this windows api can handle:
    https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

    The SendKeys class is very nice, but it's also limited. The approach above sends the key command directly to Windows OS.

提交回复
热议问题