因此,此代码已经可以用于设置我的代理Pac,但问题是RegKey.SetValue(“ AutoConfigURL”)或RegKey.DeleteValue(“ AutoConfigURL”)仅可使用1次。
因此,我需要重新运行我的应用以进行删除或重新设置。 即使我使用Form Closing,如果我先设置SetValue值,还是先对按钮进行操作。第二次它不起作用。
我缺少什么吗?
[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;
bool settingsReturn, refreshReturn;
public VPNForm()
{
InitializeComponent();
ConnectionChecker();
}
//When Button Click On or Off By Button Text
private void VPNButton_Click(object sender, EventArgs e)
{
RegistryKey RegKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", RegistryKeyPermissionCheck.ReadWriteSubTree);
if (VPNButton.Text == "ON")
{
RegKey.SetValue("AutoConfigURL", "mypaclink/proxy.pac");
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
else
{
if(RegKey.GetValue("AutoConfigURL") != null)
{
RegKey.DeleteValue("AutoConfigURL");
}
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
}
RegKey.Close();
ConnectionChecker();
}
//Delete Proxy Setting
private void VPNForm_FormClosing(object sender, FormClosingEventArgs e)
{
RegistryKey RegKey2 = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (RegKey2.GetValue("AutoConfigURL") != null)
{
RegKey2.DeleteValue("AutoConfigURL");
}
settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
RegKey2.Close();
}
//Check Condition Proxy is ON or OFF
public void ConnectionChecker()
{
RegistryKey RegKey3 = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
if (RegKey3.GetValue("AutoConfigURL") == null)
{
VPNButton.Text = "ON";
ConnectionLabel.Text = "Disconnected";
}
else
{
VPNButton.Text = "OFF";
ConnectionLabel.Text = "Connected";
}
RegKey3.Close();
}
编辑#1:
所以我发现问题不在我的代码内,而在我自己的PC上,只有5台PC属于我。 Dunno为什么,现在我正尝试将其从Windows 7升级到Windows10。如果有人知道如何找到问题,请告诉我,谢谢。 我使用4台Windows 7 PC和1台Windows 10 All Works。.
答案 0 :(得分:0)
尽管您在评论中提到它可以在其他PC上运行,但对我来说,以下代码中的逻辑似乎是相反的:
if (RegKey3.GetValue("AutoConfigURL") == null)
{
VPNButton.Text = "ON";
ConnectionLabel.Text = "Disconnected";
}
else
{
VPNButton.Text = "OFF";
ConnectionLabel.Text = "Connected";
}
应该不是:
if (RegKey3.GetValue("AutoConfigURL") != null) // Reversed the check here
{
VPNButton.Text = "ON";
ConnectionLabel.Text = "Disconnected";
}
else
{
VPNButton.Text = "OFF";
ConnectionLabel.Text = "Connected";
}
希望有帮助!