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

旧城冷巷雨未停 提交于 2019-12-01 18:47:34

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!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!