C# 为什么我不能更改代码中的音量?
我试图通过编程方式更改PC上的音量,但这段代码没有结果,我按照此处()的另一个答案来执行此操作。调用函数时没有错误,但什么也没有发生,有人能帮忙吗C# 为什么我不能更改代码中的音量?,c#,.net,audio,C#,.net,Audio,我试图通过编程方式更改PC上的音量,但这段代码没有结果,我按照此处()的另一个答案来执行此操作。调用函数时没有错误,但什么也没有发生,有人能帮忙吗 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace UnRestrict.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace UnRestrict.Forms
{
static class Sounds
{
//hexidecimal values for the values needed
private const int VOLUP = 0xA0000;
private const int VOLDOWN = 0x90000;
private const int VOLMUTE = 0x80000;
private const int APPCMND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
public static void VolumeUp()
{
SendMessageW(IntPtr.Zero, APPCMND, IntPtr.Zero, (IntPtr) VOLUP);
}
public static void VolumeDown()
{
SendMessageW(IntPtr.Zero, APPCMND, IntPtr.Zero, (IntPtr)VOLDOWN);
}
public static void VolumeMute()
{
SendMessageW(IntPtr.Zero, APPCMND, IntPtr.Zero, (IntPtr)VOLMUTE);
}
}
}
我修复了它,在尝试之前,我在某个地方读到,
SendMessageW()
对hwnd
和wParam
参数不做任何操作,您可以向它传递一个空指针(IntPtr.Zero)
。这就是我错的地方。我将IntPtr.Zero值更改为Process.GetCurrentProcess().Handle
,现在一切都好了
奇怪的是,返回的vlaue仍然不是“1”,但我也读到这可能是正常的
最终代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UnRestrict.Forms
{
static class Sounds
{
//hexidecimal values for the values needed
private const int VOLUP = 0xA0000;
private const int VOLDOWN = 0x90000;
private const int VOLMUTE = 0x80000;
private const int APPCMND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessageW(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
public static void VolumeUp()
{
int val = (Int32)SendMessageW(Process.GetCurrentProcess().Handle, APPCMND, Process.GetCurrentProcess().Handle, (IntPtr)VOLUP);
}
public static void VolumeDown()
{
SendMessageW(Process.GetCurrentProcess().Handle, APPCMND, Process.GetCurrentProcess().Handle, (IntPtr)VOLDOWN);
}
public static void VolumeMute()
{
SendMessageW(Process.GetCurrentProcess().Handle, APPCMND, Process.GetCurrentProcess().Handle, (IntPtr)VOLMUTE);
}
}
}
当您不检查返回值时,如何知道没有错误?我将如何做?我读到IntPtr只是一个类似指针的对象,那么如何检查是否有错误?Win32有重载返回类型的习惯。
SendMessage
的返回类型与本机指针的宽度相同(因此您使用IntPtr
),但这并不意味着该值本身就是指针。您应该将返回的IntPtr
强制转换为一个int,然后将其与MSDN()上记录的返回值进行比较,后者表示如果成功(TRUE
是1
的Win32宏),那么您的代码应该是:bool ok=(Int32)SendMessageW(…)==1
。如果失败,请致电GetLastError
。谢谢。作为一个傻瓜,我从来没有想到过!我要试一试!糟糕的是,我看错了。好的,所以它无法发送。。。去谷歌我去!