用VB开发打开指定网页的EXE程序触发Win32Exception报错如何解决
问题原因
你当前代码的核心问题是传入的网址没有带http://或https://协议头:System.Diagnostics.Process.Start在接收无协议头的字符串时,会将其识别为本地文件路径进行查找,自然会抛出「找不到指定文件」的Win32异常。
最简单的修复方案
直接给网址补充协议头即可,修改按钮点击事件的代码如下:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click System.Diagnostics.Process.Start("https://www.google.com") End Sub
如果你使用的是.NET Core 3.0+、.NET 5/6/7/8等更高版本的.NET平台,还需要手动开启ShellExecute才能正常调用默认浏览器,更稳妥的通用写法如下:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim startInfo As New ProcessStartInfo("https://www.google.com") startInfo.UseShellExecute = True Process.Start(startInfo) End Sub
其他实现打开网页的方案
- 强制指定特定浏览器打开:如果不需要调用默认浏览器,要固定用某款浏览器打开网页,可以直接指定浏览器执行文件,把网址作为参数传入:
' 示例为固定用Edge打开,Chrome替换为chrome.exe,火狐替换为firefox.exe即可 System.Diagnostics.Process.Start("msedge.exe", "https://www.google.com") - 调用系统ShellExecute API实现(兼容性最优):适合需要兼容旧版本.NET框架、旧系统的场景,通过调用Windows原生API实现打开网页,稳定性更高:
' 首先引入API声明 Imports System.Runtime.InteropServices Public Class Form1 <DllImport("shell32.dll", SetLastError:=True)> Private Shared Function ShellExecute(hWnd As IntPtr, lpOperation As String, lpFile As String, lpParameters As String, lpDirectory As String, nShowCmd As Integer) As IntPtr End Function Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' 1代表窗口正常展示打开 ShellExecute(IntPtr.Zero, "open", "https://www.google.com", Nothing, Nothing, 1) End Sub End Class
内容的提问来源于stack exchange,提问作者pomahajbo
相关产品推荐
相关产品推荐

