Como Desativar WebBrowser 'Clique' na sua aplicação só
Pergunta
O 'clique' em questão é, na verdade, um amplo sistema de preferência, assim que eu apenas quero que ele seja desativado quando a minha candidatura tem o foco e, em seguida, re-ativar quando o aplicativo fecha/perde o foco.
Originalmente, eu queria fazer esta pergunta aqui no stackoverflow, mas eu ainda não estava na versão beta.Assim, depois de googling para a resposta e encontrar apenas um pouco de informação sobre ela me veio com a seguinte e resolvi postar aqui agora que eu estou no beta.
using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
Em seguida, no formulário principal, utilizamos o código acima em 3 eventos:
- Ativado
- Desativado
FormClosing
private void Form1_Activated(object sender, EventArgs e) { // Disable the sound when the program has focus WebClickSound.Enabled = false; } private void Form1_Deactivate(object sender, EventArgs e) { // Enable the sound when the program is out of focus WebClickSound.Enabled = true; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Enable the sound on app exit WebClickSound.Enabled = true; }
O único problema que eu vejo atualmente é se o programa falha eles não tem o som do clique até que eles re-lançamento do meu aplicativo, mas eles não sabem fazer isso.
O que vocês acham?Esta é uma boa solução?Que melhorias podem ser feitas?
Solução
Tenho notado que, se você usar o WebBrowser.Documento.Escrever, ao invés de incluir WebBrowser.DocumentText, em seguida, o som de clique não acontece.
Assim, em vez de este:
webBrowser1.DocumentText = "<h1>Hello, world!</h1>";
tente isso:
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<h1>Hello, world!</h1>");
Outras dicas
const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
const int SET_FEATURE_ON_PROCESS = 0x00000002;
[DllImport("urlmon.dll")]
[PreserveSig]
[return: MarshalAs(UnmanagedType.Error)]
static extern int CoInternetSetFeatureEnabled(int FeatureEntry,
[MarshalAs(UnmanagedType.U4)] int dwFlags,
bool fEnable);
static void DisableClickSounds()
{
CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,
SET_FEATURE_ON_PROCESS,
true);
}
Você desativá-lo alterando o Internet Explorer valor do registro de navegação de som para "NULL":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","NULL");
E habilitá-lo alterando o Internet Explorer valor do registro de navegação som "C:\Windows\Media\Cityscape\Windows Navegação de Início.wav":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","C:\Windows\Media\Cityscape\Windows Navigation Start.wav");
Definitivamente se sente como um hack, mas ter feito alguma pesquisa sobre isso há muito tempo atrás e não encontrar outras soluções, provavelmente, a sua melhor aposta.
Melhor ainda seria projetar seu aplicativo para que ele não necessita de muitas chato página recarrega..por exemplo, se você estiver atualizando de um iframe para verificar se há atualizações no servidor, use XMLHttpRequest em vez disso.(Você pode dizer que eu estava lidando com esse problema de volta nos dias que antecedem o termo "AJAX" foi cunhado?)
Se você deseja usar a substituição de Registro do Windows, utilize esta opção:
// backup value
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string BACKUP_keyValue = (string)key.GetValue(null);
// write nothing
key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, "", RegistryValueKind.ExpandString);
// do navigation ...
// write backup key
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, BACKUP_keyValue, RegistryValueKind.ExpandString);