我在 Windows 10 上使用來自 32 位 Excel 365 的 VBA。
假設我有一個記事本視窗的句柄hWndApp,為什么下面沒有設定視窗的標題?相反,它似乎什么都不做。
Private Declare Function SetWindowText Lib "user32" _
Alias "SetWindowTextA" _
(ByVal hwnd As Long, ByVal _
lpString As String) As Long
Call SetWindowText(hWndApp, "The handle to notepad is " & CStr(hWndApp))
uj5u.com熱心網友回復:
請關閉所有記事本會話,打開一個新的空記事本視窗并運行下一個代碼。檢查任務管理器是否存在任何隱藏的此類行程并殺死它(如果有):
Sub testChangeNotepadTitle()
Dim hWndApp As Long
hWndApp = FindWindow(vbNullString, "Untitled - Notepad"): Debug.Print hWndApp
SetWindowText hWndApp, "The handle to notepad is " & CStr(hWndApp)
End Sub
不行嗎?如果它有效,這僅意味著您使用的視窗句柄是錯誤的......
您可能打開了更多記事本視窗,API 找到了第一個視窗,而不是您認為的那個視窗...
uj5u.com熱心網友回復:
作為已接受答案的最新補充,有條件編譯的示例同時滿足MS Office 2010 (關鍵字VBA7)和其他/舊版本(例如 Office 2007)的要求。
下的API函式VBA7正式做需求LongPtr為指標型別到→手柄或→存盤位置(注意特殊PtrSafe前綴!)。
因此,一個視窗句柄被宣告為LongPtr在Office 2010或更高,并且因為Long在之前的版本中; 因此,有必要通過條件編譯常量(#If VBA7 Then .. #End If)區分不同版本。-
注意:結合這些可能性還可能需要在用戶程序中區分變數宣告 (cf testChangeNotepadTitle)
提示: LongPtr不是真正的資料型別,因為它會根據實際的 32/64 位環境轉換為正確的資料型別。
請注意,64 位系統可以安裝為 32 位辦公室或 64 位辦公室。LongPtr 支持撰寫可在 32 位和 64 位環境中運行的可移植代碼。
旁注:在某些特殊情況下(例如,在 32 位和 64 位系統上加載兩個不同的 dll 或使用具有不同簽名的函式)很少需要該#If Win64指令VBA7。
API函式
Option Explicit ' declaration head of code module
#If VBA7 Then ' MS Office 2010
Private Declare PtrSafe Function FindWindow Lib "user32" _
Alias "FindWindowA" ( _
ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function SetWindowText Lib "user32" _
Alias "SetWindowTextA" ( _
ByVal hwnd As LongPtr, _
ByVal lpString As String) As Long
#Else
Private Declare Function FindWindow Lib "user32" _
Alias "FindWindowA" ( _
ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SetWindowText Lib "user32" _
Alias "SetWindowTextA" ( _
ByVal hwnd As Long, _
ByVal lpString As String) As Long
#End If
呼叫程式 testChangeNotepadTitle
Sub testChangeNotepadTitle()
Const NotePadTitle As String = "Untitled - Notepad" ' EN-US
'Const NotePadTitle As String = "Unbenannt - Editor" ' DE
#If VBA7 Then
Dim hwndapp As LongPtr
#Else
Dim hwndapp As Long
#End If
hwndapp = FindWindow(vbNullString, NotePadTitle): Debug.Print hwndapp
SetWindowText hwndapp, "The handle to notepad is " & CStr(hwndapp)
End Sub
旁注 視窗標題“無標題-記事本”遵循區域設定;所以我添加了一個例子,例如德國/奧地利(DE) - 標題為“Unbenannt - Editor” - 作為注釋程式常量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/346663.html
標籤:vba
