I'am currently trying to make a little program, which changes my standard audio device from my USB Headset to my Speakers. After using Regshot to locate the registry keys that are changed by manually switching the audio devices, I was able to find out the binary codes for my Speaker and Headset.
static void Main(string[] args)
{
RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\{02b3c792-0c05-486c-be02-2ded778dc236}", true);
standarddevice.SetValue("Role:0", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
standarddevice.SetValue("Role:1", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
standarddevice.SetValue("Role:2", "DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}
The Problem, which I'am not able to solve, is that I get a "Object reference not set to an instance of an object" Error.
It's most likely because the specified key does not exist.
Check out the documentation: http://msdn.microsoft.com/en-us/library/z9f66s0a(v=vs.110).aspx
OpenSubKey
will return null
if the Open
operation fails.To resolve this, you should check for null and do the appropriate thing, perhaps:
RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\" +
"{02b3c792-0c05-486c-be02-2ded778dc236}", true);
if (standardDevice != null)
{
standarddevice.SetValue("Role:0",
"DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
standarddevice.SetValue("Role:1",
"DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
standarddevice.SetValue("Role:2",
"DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}
If you see that the key does actually exist, it's possibly under the Wow6432Node if you're on a 64-bit machine. In that case you can try something like:
RegistryKey standarddevice = Registry.LocalMachine.OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render\\" +
"{02b3c792-0c05-486c-be02-2ded778dc236}", true);
if (standardDevice == null)
{
standarddevice = Registry.LocalMachine.OpenSubKey(
"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\" +
"Audio\\Render\\{02b3c792-0c05-486c-be02-2ded778dc236}", true);
}
if (standardDevice != null)
{
standarddevice.SetValue("Role:0",
"DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
standarddevice.SetValue("Role:1",
"DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
standarddevice.SetValue("Role:2",
"DF 07 01 00 04 00 08 00 16 00 01 00 14 00 55 01", RegistryValueKind.Binary);
}