如何在使用Process.Start启动内容后更改窗口标题?
Dim myProc as Process
myProc = myProc.Start("NotePad.exe")
不幸的是myProc.MainWindowTitle = "Fancy Notepad"
不起作用,因为这是只读的。那怎么办呢?
答案 0 :(得分:2)
您无法使用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")
在更改窗口标题之前,您需要等待几毫秒,否则窗口标题不会更改。
答案 1 :(得分:1)
您需要使用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秒)。更好的方法是主动检测窗口何时被创建,但这超出了这个问题的范围。
答案 2 :(得分:0)
以上所有原因均由于各种原因而失败-无法找到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