Can you explain why the last line is not the same as the previous two lines and doesn't work? (it doesn't find any window)
Private Declare PtrSafe Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As LongPtr, ByVal hWnd2 As LongPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As LongPtr
Working = FindWindowEx(hWnd2, 0&, "EXCEL7", vbNullString)
Working = FindWindowEx(hWnd2, 0&, "EXCEL7", CStr(vbNullString))
NotWorking = FindWindowEx(hWnd2, 0&, "EXCEL7", CStr(IIf(1 = 1, vbNullString, vbNullString)))
CodePudding user response:
I experimented a bit. First: I can confirm the behavior.
Then I had a closer look to the difference. I used an intermediate variable to store the 4th parameter and dumped some information. My conclusion: vbNullString
returns a null pointer (and CStr(vbNullString)
).
However, the IIF-function will not return a null pointer: It needs to copy the content of either the if or the else branch to a new location (a new memory address). The content at this location is again an empty string, but it seems that FindWindowEx
does something with it (I am not really familiar with that function).
Const Windowname = "IrfanView" ' Had to change that
Dim res
Dim hWnd2 As LongPtr
Dim nullStr As String
nullStr = vbNullString
res = FindWindowEx(hWnd2, 0&, Windowname, nullStr)
Debug.Print VarType(res), res, VarType(nullStr), StrPtr(nullStr)
nullStr = CStr(vbNullString)
res = FindWindowEx(hWnd2, 0&, Windowname, nullStr)
Debug.Print VarType(res), res, VarType(nullStr), StrPtr(nullStr)
nullStr = IIf(1 = 1, vbNullString, vbNullString)
res = FindWindowEx(hWnd2, 0&, Windowname, nullStr)
Debug.Print VarType(res), res, VarType(nullStr), StrPtr(nullStr)
Output:
20 4134988 8 0
20 4134988 8 0
20 0 8 2346722344360