Refresh browser's page programmatically, from a .Net WinForms application

后端 未结 2 993
盖世英雄少女心
盖世英雄少女心 2021-01-19 14:35

From asp.net page, via ClickOnce deployment, a .Net WinForms application is started. At a certain point the WinForm application needs to refresh the web page it was started

相关标签:
2条回答
  • 2021-01-19 15:04

    Here's some sample code to do what you need (just the relevant parts):

    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            // Get a handle to an application window.
            [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
            public static extern IntPtr FindWindow(string lpClassName,
                string lpWindowName);
    
            // Activate an application window.
            [DllImport("USER32.DLL")]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
    
    
            private void RefreshExplorer()
            {
                //You may want to receive the window caption as a parameter... 
                //hard-coded for now.
                // Get a handle to the current instance of IE based on window title. 
                // Using Google as an example - Window caption when one navigates to google.com 
                IntPtr explorerHandle = FindWindow("IEFrame", "Google - Windows Internet Explorer");
    
                // Verify that we found the Window.
                if (explorerHandle == IntPtr.Zero)
                {
                    MessageBox.Show("Didn't find an instance of IE");
                    return;
                }
    
                SetForegroundWindow(explorerHandle );
                //Refresh the page
                SendKeys.Send("{F5}"); //The page will refresh.
            }
        }
    }
    

    Note: The code is a modification of this MSDN example.

    0 讨论(0)
  • 2021-01-19 15:15

    This is not easy to do in a way that is robust. Users may not be using IE, for example.

    The only thing you control and that is common to the web page and the windows app is your web server.

    This solution is convoluted, but is the only way I can think of that would work.

    1) Get the web page to open a long-polling connection to the web server before the windows app runs. SignalR is getting good press for this at the moment.

    2) Get the windows app to send a signal to the server when it wants to update the web page.

    3) On the server, complete the long-polling request, sending a signal back to the web browser.

    4) In the web page, handle the response by refreshing the page.

    I said it was convoluted!

    0 讨论(0)
提交回复
热议问题