C# Simulate VolumeMute press

不羁岁月 提交于 2019-12-05 08:26:26

The first reason it doesn't work is because you use the wrong DLL, coredll.dll is Windows Mobile. In the desktop version of Windows, keybd_event is exported by user32.dll. The second reason it doesn't work is because sending the keystroke isn't good enough. Not quite sure why, this seems to be intercepted before the generic input handler.

You can use WM_APPCOMMAND, it supports a range of commands and APPCOMMAND_VOLUME_MUTE is one of them. It acts as a toggle, turning muting on and off. Make your code look like this:

    private void button1_Click(object sender, EventArgs e) {
        var msg = new Message();
        msg.HWnd = this.Handle;
        msg.Msg = 0x319;              // WM_APPCOMMAND
        msg.WParam = this.Handle;
        msg.LParam = (IntPtr)0x80000; // APPCOMMAND_VOLUME_MUTE
        this.DefWndProc(ref msg);
    }

This code needs to be inside a instance method of the form, note how it uses DefWndProc(). If you want to put it elsewhere then you need to fallback to SendMessage(). The actual window handle doesn't matter, as long as it is a valid toplevel one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!