Search code examples
c#winapiwininetdial-up

Dial-up using wininet.dll Windows API issue (C#)


I'm calling the following function on wininet.dll in order to get online (C# pinvoke):

[DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int InternetDial(IntPtr hWndParent, string pszEntryName,
                                   int dwFlags, ref int lpdwConnection,
                                   int ReservedValue);

 public static bool GetOnline()
 {
        int connectionID = 0;
        InternetDial(IntPtr.Zero, "DefaultDialUp", INTERNET_AUTODIAL_FORCE_UNATTENDED, ref connectionID, 0);
        return (connectionID != 0);
 }

The problem is when error occurs in the dial up process, such as hardware failure,
Windows shows a blocking dialog that ask the user how to procceed,
And my function is stuck until the user causes the dialog to be closed:
enter image description here This code should be deployed on automatic systems so this is a major issue for me...

I'm looking for a way to suppress the error dialogs on the windows API level..

Thanks in advance, Eitan.


Solution

  • Iv'e managed to find a workaruond for the issue, but it's pretty nasty,
    better solutions still welcome...

        const int WM_CLOSE = 0x10;
        const int INTERNET_AUTODIAL_FORCE_UNATTENDED = 0x2;
    
        [DllImport("User32.dll", EntryPoint = "PostMessage")]
        public static extern int PostMessage(int hWnd, int Msg, IntPtr wParam, IntPtr lParam);
    
        [DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern int InternetDial(IntPtr hWndParent, string pszEntryName, int dwFlags, ref int lpdwConnection, int ReservedValue);
    
            public static bool GetOnline()
            {
                connectionID = 0;
                Form f = null;
                var t = new Thread((ParameterizedThreadStart)delegate
                {
                    f = new Form();                
                    InternetDial(f.Handle, "DefaultDialUp", INTERNET_AUTODIAL_FORCE_UNATTENDED, ref connectionID, 0);
                });
                t.Start();
                t.Join(23000); //wait 23 seconds before closing the window
                f.Invoke((EventHandler)delegate {
                    PostMessage(f.Handle.ToInt32(), WM_CLOSE, IntPtr.Zero, IntPtr.Zero);            
                });
                t.Join();            
                return (connectionID != 0);            
            }