VC 让进程/网页静音的方法

类似一些浏览器的静音功能,代码如下:

// 这种方式静音后, 只能通过刷新网页才能恢复声音,而且只在XP下有效。Vista以上版本可用mixerSetControlDetails实现

 

BOOL SetMute(BOOL bMute){
 HMODULE hDSound;
 HMODULE hWinmm;
 void* pDirectSoundCreate = NULL;
 void* pmidiStreamOpen  = NULL;
 void* pmidiStreamOut  = NULL;
 void* pwaveOutWrite  = NULL;
 BYTE byMute[]   = {0xC2, 0x0C, 0x00}; //ASM RET 0
 BYTE byRestore[]   = {0x8B, 0xFF, 0x55};
 DWORD OldProtect;

 hDSound = LoadLibrary(_T("DSound.dll"));
 if (NULL != hDSound)
 {
 pDirectSoundCreate = GetProcAddress(hDSound, "DirectSoundCreate");
 if (pDirectSoundCreate != NULL)
 {
 VirtualProtect(pDirectSoundCreate, 3, PAGE_EXECUTE_READWRITE, &OldProtect);

 if (!bMute)
 CopyMemory(pDirectSoundCreate, byRestore, 3);
 else
 CopyMemory(pDirectSoundCreate, byMute, 3);

 VirtualProtect(pDirectSoundCreate, 3, PAGE_EXECUTE_READ, &OldProtect);
 }

 FreeLibrary(hDSound);
 }
 else
 {
 return FALSE;
 }

 hWinmm = LoadLibrary(_T("Winmm.dll"));
 if (NULL != hWinmm)
 {
 pmidiStreamOpen = GetProcAddress(hWinmm, "midiStreamOpen");
 pmidiStreamOut = GetProcAddress(hWinmm, "midiStreamOut");
 pwaveOutWrite = GetProcAddress(hWinmm, "waveOutWrite");

 if (pmidiStreamOpen != NULL)
 {
 VirtualProtect(pmidiStreamOpen, 3, PAGE_EXECUTE_READWRITE, &OldProtect);

 if (!bMute)
 CopyMemory(pmidiStreamOpen, byRestore, 3);
 else
 CopyMemory(pmidiStreamOpen, byMute, 3);

 VirtualProtect(pmidiStreamOpen, 3, PAGE_EXECUTE_READ, &OldProtect);
 }
 if (pmidiStreamOut != NULL)
 {
 VirtualProtect(pmidiStreamOut, 3, PAGE_EXECUTE_READWRITE, &OldProtect);

 if (!bMute)
 CopyMemory(pmidiStreamOut, byRestore, 3);
 else
 CopyMemory(pmidiStreamOut, byMute, 3);

 VirtualProtect(pmidiStreamOut, 3, PAGE_EXECUTE_READ, &OldProtect);
 }
 if (pwaveOutWrite != NULL)
 {
 VirtualProtect(pwaveOutWrite, 3, PAGE_EXECUTE_READWRITE, &OldProtect);

 if (!bMute)
 CopyMemory(pwaveOutWrite, byRestore, 3);
 else
 CopyMemory(pwaveOutWrite, byMute, 3);

 VirtualProtect(pwaveOutWrite, 3, PAGE_EXECUTE_READ, &OldProtect);
 }

 FreeLibrary(hWinmm);
 }
 else
 {
 return FALSE;
 }

 return TRUE;

}

 

上面代码有弊端,不过可以作为参考学习。

要实现程序的静音,可以使用detours.lib中的方法来实现(适用于XP),例子如链接:http://www.pudn.com/downloads493/sourcecode/internet/browser/49636978browser_mute.rar

你可能感兴趣的:(VC 让进程/网页静音的方法)