我想启动MS Edge浏览器并过一会儿将其关闭。我已经尝试了一些诸如Microsoft Internet Controls之类的方法。但是我需要与IE不同的浏览器。
Dim pi As New Process
pi = Process.Start("shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge")
Threading.Thread.Sleep(1000)
pi.CloseMainWindow() ' -> NullReferenceException
但是即使我已经初始化了它,我总是会得到一个空引用异常。
有人可以帮忙吗?
我建议您使用GetProcessesByName获取该进程,然后尝试杀死它。
示例代码:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
System.Diagnostics.Process.Start("microsoft-edge:http://localhost/")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim p As Process() = Process.GetProcessesByName("MicrosoftEdge")
For i = 0 To p.Count - 1
p(i).Kill()
Next
End Sub
End Class
输出:
让我知道我是否误解了什么。我将尝试纠正自己。
MainWindowHandle
属性在使用此类应用程序时无用。您需要获取子窗口的句柄:
致谢
源c#代码是@ B.K。在Minimize Microsoft Edge browser from C# not working中的回答中发布。我只是将相关代码转换为vb.net,并将最小化部分替换为此帖子的结尾部分。
Imports System.Runtime.InteropServices
Imports System.Threading
Imports System.Text
'//
'Required declarations, win32 APIs, and delegate:
Private Const WM_CLOSE As UInteger = &H10
Private Delegate Function EnumWindowsProc(ByVal hWnd As IntPtr,
ByVal lParam As IntPtr) As Boolean
<DllImport("user32.dll")>
Private Shared Function EnumWindows(ByVal enumProc As EnumWindowsProc,
ByVal lParam As IntPtr) As Boolean
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
Private Shared Function GetClassName(ByVal hWnd As IntPtr,
ByVal lpClassName As StringBuilder,
ByVal nMaxCount As Integer) As Integer
End Function
<DllImport("user32.dll", CharSet:=CharSet.Unicode)>
Private Shared Function GetWindowTextLength(ByVal hWnd As IntPtr) As Integer
End Function
<DllImport("user32.dll", CharSet:=CharSet.Unicode, SetLastError:=True)>
Private Shared Function GetWindowText(ByVal hWnd As IntPtr,
ByVal lpString As StringBuilder,
ByVal nMaxCount As Integer) As Integer
End Function
<DllImport("user32.dll")>
Private Shared Function SendMessage(ByVal hWnd As IntPtr,
ByVal msg As Integer,
ByVal wp As IntPtr,
ByVal lp As IntPtr) As IntPtr
End Function
并且在按钮的单击事件中:
Dim s As String = "microsoft-edge:"
'or if you want:
'Dim s As String = "microsoft-edge:https://www.google.com"
Process.Start(s)
Thread.Sleep(1000)
Dim targetClass As String = "ApplicationFrameWindow"
Dim tarWindow As String = "Microsoft Edge"
EnumWindows(Function(handle, param)
Dim className = New StringBuilder(256)
GetClassName(handle, className, className.Capacity)
Dim windowTextSize As Integer = GetWindowTextLength(handle)
Dim windowText = New StringBuilder(windowTextSize + 1)
GetWindowText(handle, windowText, windowText.Capacity)
If className.ToString.Contains(targetClass) AndAlso
windowText.ToString.Contains(tarWindow) Then
SendMessage(handle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero)
End If
Return True
End Function, IntPtr.Zero)