Home > Software engineering >  How do I set the caption of a window in VBA using SetWindowText and its handle?
How do I set the caption of a window in VBA using SetWindowText and its handle?

Time:11-03

I am using VBA from 32-bit Excel 365, on Windows 10.

Assuming that I have the handle of a notepad window in hWndApp, why does the following not set the caption of the window? Rather, it appears to do nothing.

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))

CodePudding user response:

Please, close all Notepad sessions, open a new empty Notepad window and run the next code. Check in Task manager if any hidden such a process exists and kill it, if any:

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

Doesn't it work? If it works, this only mean that the window handle you use is wrong...

You maybe have more Notepad windows open and API find the first one, not the one you think it is...

  •  Tags:  
  • vba
  • Related