I would like to read the value in the "Use automatic configuration script" Address field.
I need to set the proxy for CefSharp like this
settings.CefCommandLineArgs.Add("proxy-pac-url","proxy address");
I have tried different variations of WebRequest.GetSystemWebProxy and calling function InternetQueryOption in the wininet.dll.
Code from the CefSharp repo on Github
public static class ProxyConfig
{
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool InternetQueryOption(IntPtr hInternet, uint dwOption, IntPtr lpBuffer, ref int lpdwBufferLength);
private const uint InternetOptionProxy = 38;
public static InternetProxyInfo GetProxyInformation()
{
var bufferLength = 0;
InternetQueryOption(IntPtr.Zero, InternetOptionProxy, IntPtr.Zero, ref bufferLength);
var buffer = IntPtr.Zero;
try
{
buffer = Marshal.AllocHGlobal(bufferLength);
if (InternetQueryOption(IntPtr.Zero, InternetOptionProxy, buffer, ref bufferLength))
{
var ipi = (InternetProxyInfo)Marshal.PtrToStructure(buffer, typeof(InternetProxyInfo));
return ipi;
}
{
throw new Win32Exception();
}
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(buffer);
}
}
}
}
This code works if there is a proxy in windows settings, easy to test with Fiddler.
I could read the value from the registry, but it feels like a hack
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", false);
var autoConfigUrl = registry?.GetValue("AutoConfigURL");
There must be a "correct" way to do this?
Current test code:
if (settingsViewModel.UseProxy)
{
// https://securelink.be/blog/windows-proxy-settings-explained/
RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", false);
var autoConfigUrl = registry?.GetValue("AutoConfigURL").ToString();
var proxyEnable = registry?.GetValue("ProxyEnable").ToString();
if (!string.IsNullOrEmpty(autoConfigUrl) && !string.IsNullOrEmpty(proxyEnable) && proxyEnable == "1")
{
settings.CefCommandLineArgs.Add("proxy-pac-url", autoConfigUrl);
}
else
{
var proxy = ProxyConfig.GetProxyInformation();
switch (proxy.AccessType)
{
case InternetOpenType.Direct:
{
//Don't use a proxy server, always make direct connections.
settings.CefCommandLineArgs.Add("no-proxy-server", "1");
break;
}
case InternetOpenType.Proxy:
{
settings.CefCommandLineArgs.Add("proxy-server", proxy.ProxyAddress.Replace(' ', ';'));
break;
}
case InternetOpenType.PreConfig:
{
settings.CefCommandLineArgs.Add("proxy-auto-detect", "1");
break;
}
}
}
}