【问题标题】:Refresh browser's page programmatically, from a .Net WinForms application从 .Net WinForms 应用程序以编程方式刷新浏览器页面
【发布时间】:2012-05-12 07:08:45
【问题描述】:

从 asp.net 页面,通过 ClickOnce 部署,启动一个 .Net WinForms 应用程序。 在某个时刻,WinForm 应用程序需要刷新它启动的网页。

我怎么能这样做? 基于 .Net 的 Windows 应用程序如何刷新已在浏览器中打开的页面?

【问题讨论】:

  • 如果您确实需要从 WinForms 应用程序控制 Web 浏览器,您可能应该使用 WebBrowser 控件。
  • WinForm 应用程序只提供了相关网页所属的网站所提供功能的一小部分。很不幸,没有办法,谢谢!

标签: c# winforms browser refresh


【解决方案1】:

要以稳健的方式做到这一点并不容易。例如,用户可能没有使用 IE。

您唯一可以控制的并且对网页和 Windows 应用程序通用的就是您的网络服务器。

这个解决方案很复杂,但这是我能想到的唯一可行的方法。

1) 在 Windows 应用程序运行之前,让网页打开与 Web 服务器的长轮询连接。 SignalR 目前正为此获得好评。

2) 让 windows 应用在要更新网页时向服务器发送信号。

3) 在服务器上,完成长轮询请求,向网络浏览器发送回信号。

4) 在网页中,通过刷新页面来处理响应。

我说它很复杂!

【讨论】:

  • 这可能很复杂......但这是这样做的方式。
  • 感谢您的回答。非常有趣,对我来说是全新的。我一定会试试这个。但就目前而言,我需要的是 Icarus 提出的更快的替代方案。
【解决方案2】:

这里有一些示例代码可以满足您的需要(只是相关部分):

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.
        }
    }
}

注意:代码是this MSDN example.的修改

【讨论】:

  • 感谢您的回答,我想这是我所期望的。我现在就试试。
  • @Tulinside 有许多技术可以枚举窗口并准确找到您需要的窗口。我不一定同意下面发布的关于无法“可靠”识别浏览器窗口的答案。
  • 它有效。因为我现在只需要 IE 这个解决方案就足够了。
  • @Tulinside 它适用于任何浏览器和任何版本,但显然只能在 Windows 操作系统上运行。
  • 其实没有。至少你引用的代码。例如,如果浏览器窗口没有最大化,它就不起作用。我意识到为时已晚(从我的问题的正确答案的角度来看)
猜你喜欢
  • 2011-02-14
  • 2011-02-24
  • 1970-01-01
  • 2013-08-09
  • 1970-01-01
  • 2011-02-13
  • 2018-11-14
  • 1970-01-01
  • 2014-01-25
相关资源
最近更新 更多