我有一个修改 Internet 设置的 ProxyEnable 和 ProxyServer 注册表项的类。
如果我在控制台应用程序中使用此类并运行它,则值会更改,我可以使用 regedit 查看更改。
现在不起作用的部分是我试图在 Installer 类中使用这个类,以便在安装我的应用程序期间更改注册表项。
这是该类的代码:
public class ProxySettings {
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
IntPtr lpBuffer, int dwBufferLength);
public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
public const int INTERNET_OPTION_REFRESH = 37;
static bool settingsReturn, refreshReturn;
public void EnableProxy(string proxy) {
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", proxy);
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED,
IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
public void DisableProxy() {
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 0);
registry.DeleteValue("ProxyServer", false);
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED,
IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
}
这是我的安装程序类:
[RunInstaller(true)]
public class WindowsServiceInstaller : Installer {
public WindowsServiceInstaller() {
ServiceProcessInstaller serviceProcessInstaller =
new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Password = null;
//# Service Information
serviceInstaller.DisplayName = "Client Service";
serviceInstaller.StartType = ServiceStartMode.Automatic;
//# This must be identical to the WindowsService.ServiceBase name
//# set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = "Client Service";
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
public override void Commit(System.Collections.IDictionary savedState) {
base.Commit(savedState);
ServiceController controller = new ServiceController("Client Service");
if(controller.Status != ServiceControllerStatus.Running) {
controller.Start();
}
ProxySettings proxy = new ProxySettings();
proxy.EnableProxy("127.0.0.1:8889");
}
public override void Uninstall(System.Collections.IDictionary savedState) {
base.Uninstall(savedState);
ProxySettings proxy = new ProxySettings();
proxy.DisableProxy();
}
}
在 Commit 的覆盖中,我正在启动运行良好的服务,但由于某种原因,我没有看到注册表的更改。
还要确保我添加的类正在初始化和触发
System.Diagnostics.Process.Start("http://www.microsoft.com");
到 EnableProxy 和 DisableProxy 方法。在安装过程中,网站打开,在卸载过程中也打开了,但注册表保持不变。
我究竟做错了什么?为什么它可以作为控制台应用程序运行,但不能在安装程序中运行?