本文演示如何使用 Visual C++ 的托管扩展启动默认 Internet 浏览器。
原始产品版本: Visual C++
原始 KB 数: 307382
注意
- 有关本文的 Microsoft Visual C# .NET 版本,请参阅 如何使用 Visual C# 以编程方式启动默认 Internet 浏览器。
- 本文介绍 .NET Framework 类库命名空间
System.Diagnostics.Process
和System.Windows.Forms
.
指定要打开的 URL、FTP 或文件
可以指定统一资源定位符(URL)、文件或文件传输协议(FTP)地址。 这三个分配都是有效的:
System::String * target= "http://www.microsoft.com";
System::String * target = "ftp://ftp.microsoft.com";
System::String * target = "C:\\Program Files\\Microsoft Visual Studio\\INSTALL.HTM";
使用 Process 类 Start 方法启动浏览器
该 Process
类包含静态 Start
方法。 因为它是静态方法,因此无需类的Process
实例即可调用Start
。
System::Diagnostics::Process::Start(target);
提供异常处理
由于在调用Start
方法时利用默认UseShellExecute
属性,因此无需显式查询注册表以确定哪个浏览器是默认浏览器。 但是,如果在未安装浏览器的计算机上使用此方法,则会发生异常。 必须捕获此异常,以便可以采取适当的操作。 本示例显式捕获未找到必要的注册表项时生成的错误,并指示未安装浏览器。 此外,为可能发生的其他错误提供了一个常规异常处理程序。 完整的代码示例演示了该 try...catch
块。
完整的代码示例
#using <mscorlib.dll>
#using <system.dll>
#using <System.Windows.Forms.dll>
int main()
{
//Use no more than one assignment when you test this code.
//System::String * target= "http://www.microsoft.com";
//System::String * target = "ftp://ftp.microsoft.com";
System::String * target = "C:\\Program Files\\Microsoft Visual Studio\\INSTALL.HTM";
try
{
System::Diagnostics::Process::Start(target);
}
catch (System::ComponentModel::Win32Exception * noBrowser)
{
if (noBrowser->ErrorCode==-2147467259)
System::Windows::Forms::MessageBox::Show(noBrowser->Message);
}
catch (System::Exception * other)
{
System::Windows::Forms::MessageBox::Show(other->Message);
}
return 0;
}
故障排除
此代码高度依赖于注册表HKEY_CLASSES_ROOT配置单元中的应用程序文件类型关联。 如果注册表损坏,这可能会导致意外结果和异常。 此外,文件类型和扩展可能与浏览器以外的应用程序相关联。 例如,HTM 或 Hyper Text 标记语言 (HTML) 文件可能与 Web 开发软件(而不是浏览器)相关联。