c# – 在Win 7上更改程序的音量

前端之家收集整理的这篇文章主要介绍了c# – 在Win 7上更改程序的音量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想更改程序的音量(而不是主音量).我现在有以下代码
DllImport("winmm.dll")]
public static extern int waveOutGetVolume(IntPtr hwo,out uint dwVolume);

[DllImport("winmm.dll")]
public static extern int waveOutSetVolume(IntPtr hwo,uint dwVolume);

private void volumeBar_Scroll(object sender,EventArgs e)
{
    // Calculate the volume that's being set
    int NewVolume = ((ushort.MaxValue / 10) * volumeBar.Value);
    // Set the same volume for both the left and the right channels
    uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
    // Set the volume
    waveOutSetVolume(IntPtr.Zero,NewVolumeAllChannels);
}

这仅适用于Win XP,而不适用于Windows 7(也可能不适用于Vista).我没有找到任何会在Win 7上实现相同的脚本,只是为了更改主卷(我不会追求).

解决方法

你的代码对我来说没问题(通过几个调整).这是在Windows 7 x64上运行的非常简单的WPF测试应用程序的代码

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Slider Minimum="0" Maximum="10" ValueChanged="ValueChanged"/>
    </Grid>
</Window>

C#

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ValueChanged(object sender,RoutedPropertyChangedEventArgs<double> e)
    {
        // Calculate the volume that's being set
        double newVolume = ushort.MaxValue * e.NewValue / 10.0;

        uint v = ((uint) newVolume) & 0xffff;
        uint vAll = v | (v << 16);

        // Set the volume
        int retVal = NativeMethods.WaveOutSetVolume(IntPtr.Zero,vAll);

        Debug.WriteLine(retVal);

        bool playRetVal = NativeMethods.PlaySound("tada.wav",IntPtr.Zero,0x2001);

        Debug.WriteLine(playRetVal);
    }
}

static class NativeMethods
{
    [DllImport("winmm.dll",EntryPoint = "waveOutSetVolume")]
    public static extern int WaveOutSetVolume(IntPtr hwo,uint dwVolume);

    [DllImport("winmm.dll",SetLastError = true)]
    public static extern bool PlaySound(string pszSound,IntPtr hmod,uint fdwSound);
}

当我启动应用程序并移动滑块时,“音量混合器”中会出现一个额外的音量控制,它与滑块同步地从最小值移动到最大值.

您应该检查waveOutSetVolume的返回值.如果您的代码仍无效,它可能会为您提供线索.

原文链接:https://www.f2er.com/csharp/99378.html

猜你在找的C#相关文章