马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C#控制系统的音量大小两种方法

[复制链接]
查看3978 | 回复0 | 2015-1-30 09:40:48 | 显示全部楼层 |阅读模式
方法一:改变程序音量,但不改变系统音量设置

[C#] 纯文本查看 复制代码
[DllImport("Winmm.dll")]
private static extern int waveOutSetVolume(int hwo, System.UInt32 pdwVolume);
 
[DllImport("Winmm.dll")]
private static extern uint waveOutGetVolume(int hwo, out    System.UInt32 pdwVolume);  
#region 
 
private int volumeMinScope = 0;
private int volumeMaxScope = 100;
private int volumeSize = 100;
 
/// <summary>
/// 音量控制,但不改变系统音量设置
/// </summary>
public int VolumeSize
{
    get { return volumeSize; }
    set { volumeSize = value; }
}
 
public void SetCurrentVolume()
{
    if (volumeSize < 0)
    {
        volumeSize = 0;
    }
 
    if (volumeSize > 100)
    {
        volumeSize = 100;
    }
    System.UInt32 Value = (System.UInt32)((double)0xffff * (double)volumeSize / (double)(volumeMaxScope - v           
 
              olumeMinScope));//先把trackbar的value值映射到0x0000~0xFFFF范围
 
 
    //限制value的取值范围
    if (Value < 0)
    {
        Value = 0;
    }
 
    if (Value > 0xffff)
    {
        Value = 0xffff;
    }
 
    System.UInt32 left = (System.UInt32)Value;//左声道音量
    System.UInt32 right = (System.UInt32)Value;//右
    waveOutSetVolume(0, left << 16 | right); //"<<"左移,“|”逻辑或运算
}


方法二:改变系统音量设置
[C#] 纯文本查看 复制代码
[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);
 
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;
 
/// <summary>
/// 改变系统音量大小,增加
/// </summary>
public 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);
}
 
/// <summary>
/// 改变系统音量大小,减小
/// </summary>
public 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);
}
 
/// <summary>
/// 改变系统音量大小,静音
/// </summary>
public 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);
}


C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则