使用 Process.Start 启动某些内容后如何更改窗口标题?
Dim myProc as Process
myProc = myProc.Start("NotePad.exe")
不幸的是myProc.MainWindowTitle = "Fancy Notepad"
不起作用,因为这是只读的。那么怎么做呢?
您不能使用更改窗口标题,Process.MainWindowTitle
因为该属性是readonly。
为了更改窗口标题,您首先需要获取目标窗口的句柄,然后使用 Win32 API 函数指示操作系统更改与该句柄关联的窗口的标题,SetWindowsText
如下所示
<DllImport("user32.dll")> _
Shared Function SetWindowText(ByVal hwnd As IntPtr, ByVal windowName As String) As Boolean
End Function
一旦你定义了上面的函数,你就可以使用以下代码继续操作窗口标题:
Dim process As New Process()
process.StartInfo.FileName = "notepad.exe"
process.Start()
Thread.Sleep(100)
SetWindowText(process.MainWindowHandle, "Fancy Notepad")
在更改窗口标题之前您需要等待几毫秒,否则窗口标题将不会更改。
您需要使用 Win32API 调用SetWindowText()
VB.Net 导入:
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SetWindowText(ByVal hwnd As IntPtr, ByVal lpString As String) As Boolean
End Function
使用示例:
myProc.Start("notepad.exe")
'Note #1
SetWindowText(myProc.MainWindowHandle, "h4x3d title")
#1:在尝试设置窗口文本之前,您需要留出时间让进程开始。如果您在创建窗口之前设置文本,它似乎什么都不做。最简单的方法是让线程休眠任意时间(例如 1 秒)。更好的方法是主动检测窗口何时创建,但这超出了这个问题的范围。
由于各种原因,上述所有操作都失败了 - 找不到 HWND,或者在慢速 PC 上睡眠时间不够长。像这样称呼它。它重试直到读回标题:
<DllImport("user32.dll")>
Shared Function SetWindowText(ByVal hwnd As IntPtr, ByVal windowName As String) As Boolean
End Function
SetWindowTextCall(SomeProcess.MainWindowHandle, "Name of Windows")
''' SetWindowTextCall is here to wrap the SetWindowtext API call. This call fails when there is no
''' hwnd as Windows takes its sweet time to get that. It has a counter to make sure we do not get stuck
''' </summary>
''' <param name="hwnd">Handle to the window to change the text on</param>
''' <param name="windowName">the name of the Window </param>
'''
Public Function SetWindowTextCall(hwnd As IntPtr, windowName As String) As Boolean
Dim status As Boolean = False
Dim WindowCounter As Integer = 0
While Not status
Try
Thread.Sleep(100)
status = SetWindowText(hwnd, windowName)
Catch ' can fail to be a valid window handle
Return False
End Try
WindowCounter = WindowCounter + 1
If WindowCounter > 200 Then ' 20 seconds
status = True
End If
End While
Return True
End Function