使用 CStr(IIF(....)) 调用带有参数的 Windows API 函数不起作用。为什么?



你能解释一下为什么最后一行和前两行不一样,不能工作吗?(它没有找到任何窗口)

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

我做了一些实验。首先:我可以确认行为。

然后我仔细看了看差异。我使用一个中间变量来存储第4个参数并转储一些信息。我的结论是:vbNullString返回一个空指针(和CStr(vbNullString))。

但是,iif函数不会返回空指针:它需要将if分支或else分支的内容复制到一个新的位置(一个新的内存地址)。在这个位置的内容再次是一个空字符串,但似乎FindWindowEx用它做了一些事情(我不太熟悉那个函数)。
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)

输出:

20            4134988       8             0 
20            4134988       8             0 
20            0             8             2346722344360

最新更新