如何关闭外部Web浏览器中的选项卡?

Tom*_*m K 7 c# browser wpf oauth process

我正在编写一个桌面应用程序,在一部分中我将介绍OAuth 2.0流程.

步骤是:

  1. 启动过程 - 使用登录页面打开Web浏览器.
  2. 用户登录并授权我的应用程序.
  3. 在后台我搜索具有特定名称的进程,在应用程序中保存它(名称).
  4. 最后,我关闭了Web浏览器.

问题是,如果用户之前在Web浏览器中打开了一些选项卡 - 在第1点中添加了新选项卡,在第4点中.所有内容都已关闭(带有所有选项卡的Web浏览器).

你能否告诉我是否有办法在网络浏览器中关闭一个标签?或者也许还有其他/更简单的方式来通过OAuth?

作为手动解决方案,我将向用户显示信息"现在您可以关闭此选项卡",但我想自动执行此操作.

这是C#.Net 4.0 WPF项目.

string strAuthUrl = "http://accounts.example.com/login",
       strAuthCode = string.Empty;

// Request authorization from the user (by opening a browser window):
ProcessStartInfo startInfo = new ProcessStartInfo(strAuthUrl);
startInfo.CreateNoWindow = false;

//1.        
Process.Start(startInfo);   
//2. - is happening in web browser
//3.        
do
{
    foreach (Process proc in Process.GetProcesses())
    {
        if (proc.MainWindowTitle.StartsWith("Success code="))
        {
            strAuthCode = proc.MainWindowTitle.ToString().Substring(13, 30);
//4.
            try
            {

                // Close process by sending a close message to its main window.
                proc.CloseMainWindow();
                // Free resources associated with process.
                proc.Close();
                // Wait 500 milisecs for exit
                proc.WaitForExit(500);

                //if proc has not exited so far - kill it
                if (proc.HasExited == false)
                {
                    proc.Kill();
                    proc.WaitForExit();
                }
            }
            catch (Exception ex)
            {
                //Do something with exception
            }

            break;
        }
    }
}
while (string.IsNullOrEmpty(strAuthCode));
Run Code Online (Sandbox Code Playgroud)

谢谢你的建议.

Rei*_*ldo 0

还有其他方法可以做到这一点,例如使用dotnetopenauth。但如果您确实想使用 Web 浏览器,我建议您使用 .Net WebBrowser控件来执行该任务,并处理Navigated事件以确定何时关闭它。