2015-07-19 110 views
1

在我的一個項目中,我必須得到前臺窗口的標題,所以我調用GetForegroundWindow()入口點窗體User32.dll獲取窗口句柄,然後我稱爲GetWindowText()爲標題一切都會出錯少但輸出什麼也沒有,這裏是我在我的VB.NET程序中使用的代碼。GetWindowText沒有任何返回

Imports System.Runtime.InteropServices 

Public Class Form1 

<DllImport("user32.dll")> _ 
Private Shared Function GetForegroundWindow() As IntPtr 

End Function 

<DllImport("user32.dll")> _ 
Private Shared Function GetWindowText(ByVal hwnd As Long, ByVal lpString As System.Text.StringBuilder, ByVal cch As Long) As Integer 

End Function 


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
End Sub 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 
    Dim hWnd As IntPtr 
    hWnd = GetForegroundWindow() 
    Dim title As New System.Text.StringBuilder(256) 
    GetWindowText(hWnd, title, title.Capacity) 
    Me.Text = title.ToString 
End Sub 
End Class 
+0

這是一個VB6的聲明,一箇舊的VB版本,開始作爲一個16位的開發工具。你總是可以通過看到'Long'回來。它是VB.NET中的Integer。通過訪問pinvoke.net網站獲取最新的聲明。 –

回答

1

我找到了自己的解決方案,這是爲它必須是IntPtr程序的正常運作hWnd參數爲Long值故障。新的正確代碼看起來像這樣。

Imports System.Runtime.InteropServices 

Public Class Form1 

<DllImport("user32.dll")> _ 
Private Shared Function GetForegroundWindow() As IntPtr 

End Function 

<DllImport("user32.dll")> _ 
Private Shared Function GetWindowText(ByVal hwnd As IntPtr, ByVal lpString As System.Text.StringBuilder, ByVal cch As Long) As Integer 

End Function 


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
End Sub 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick 
    Dim hWnd As IntPtr 
    hWnd = GetForegroundWindow() 
    Dim title As New System.Text.StringBuilder(256) 
    GetWindowText(hWnd, title, title.Capacity) 
    Me.Text = title.ToString 


End Sub 
End Class 
+0

你仍然沒有弄清楚。 –

+0

@HansPassant爲什麼? –

+0

正如評論中指出的那樣,Long = Integer。你錯過了cch的論點。使用該網站。 –