2015-01-09 19 views
0

我正在嘗試製作一個小程序,它將標準音頻設備從USB耳機更改爲我的揚聲器。在使用Regshot查找通過手動切換音頻設備而更改的註冊表項後,我能夠找到揚聲器和耳機的二進制代碼。註冊表值更改錯誤(對象引用未設置爲對象的實例)

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); 
    } 

的問題,這我'沒有能夠解決,是我得到一個「對象引用不設置爲一個對象的一個​​實例」錯誤。

+0

可能重複(http://stackoverflow.com/questions/4660142/what-is-a-的NullReferenceException和知識-DO-I-FIX-IT) – pmcoltrane 2015-01-09 20:05:26

回答

0

這很可能是因爲指定的鍵不存在。

退房的文檔:http://msdn.microsoft.com/en-us/library/z9f66s0a(v=vs.110).aspx

  • OpenSubKey將返回null如果Open操作失敗。

要解決這個問題,你應該檢查空和做適當的事情,也許是:

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); 
} 

如果您發現該鍵實際上確實存在,這是可能的Wow6432Node下,如果你是一臺64位機器。在這種情況下,你可以嘗試類似:什麼是一個NullReferenceException,如何解決呢]的

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); 
} 
相關問題