Search code examples
c#audiowin-universal-appvolume

Set System Volume Windows 10 in C#


i searched like hours, now i ask in this Forum.

How can I control the System Volume Setting of Windows 10?

Which Libary I need?

I am using Visual Basic 2015 and wanna programm a Windows Universal App with C#.

The programm should be able to:

  • Set Systemvolume to x%

  • increase the Systemvolume by x

  • decrease the Systemvolume by x

  • get the current Systemvolume

I found a similar Question and Answer, but the Answer doesent work.

private void Mute() {

        SendMessageW(new WindowInteropHelper(this).Handle, WM_APPCOMMAND, new WindowInteropHelper(this).Handle,
            (IntPtr)APPCOMMAND_VOLUME_MUTE);
    }

it can't find "WindowInteropHelper". But I implement:

using System;

using System.Windows.Forms;

using System.Runtime.InteropServices;


Solution

  • class VolumeChanger
    {
      private const byte VK_VOLUME_MUTE = 0xAD;
      private const byte VK_VOLUME_DOWN = 0xAE;
      private const byte VK_VOLUME_UP = 0xAF;
      private const UInt32 KEYEVENTF_EXTENDEDKEY = 0x0001;
      private const UInt32 KEYEVENTF_KEYUP = 0x0002;
    
      [DllImport("user32.dll")]
      static extern void keybd_event(byte bVk, byte bScan, UInt32 dwFlags, UInt32 dwExtraInfo);
    
      [DllImport("user32.dll")]
      static extern Byte MapVirtualKey(UInt32 uCode, UInt32 uMapType);
    
      public static void VolumeUp()
      {
         keybd_event(VK_VOLUME_UP, MapVirtualKey(VK_VOLUME_UP, 0), KEYEVENTF_EXTENDEDKEY, 0);
         keybd_event(VK_VOLUME_UP, MapVirtualKey(VK_VOLUME_UP, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
      }
    
      public static void VolumeDown()
      {
         keybd_event(VK_VOLUME_DOWN, MapVirtualKey(VK_VOLUME_DOWN, 0), KEYEVENTF_EXTENDEDKEY, 0);
         keybd_event(VK_VOLUME_DOWN, MapVirtualKey(VK_VOLUME_DOWN, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
      }
    
      public static void Mute()
      {
         keybd_event(VK_VOLUME_MUTE, MapVirtualKey(VK_VOLUME_MUTE, 0), KEYEVENTF_EXTENDEDKEY, 0);
         keybd_event(VK_VOLUME_MUTE, MapVirtualKey(VK_VOLUME_MUTE, 0), KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
      }
    }
    

    Using this, you can mute, and increase or decrease Systemvolume by 2 degree.

    I still searching a way to get the current Systemvolume.