【问题标题】:GetWindowText is returning nothingGetWindowText 什么也不返回
【发布时间】:2015-07-19 05:57:12
【问题描述】:

在我的一个项目中,我必须获得前景窗口的标题,所以我调用 GetForegroundWindow() 入口点表单 User32.dll 来获取窗口句柄,然后我调用 GetWindowText() 来获取标题,但输出的错误更少什么都没有,这是我在 VB.NET 程序中使用的代码。

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

【问题讨论】:

  • 这是一个 VB6 声明,一个旧的 VB 版本,最初是一个 16 位开发工具。您总是可以通过查看Long 来判断。它是 VB.NET 中的Integer。通过访问例如 pinvoke.net 网站获取最新的声明。

标签: vb.net dllimport hwnd entry-point


【解决方案1】:

我自己找到了解决方案,这是hWnd 参数中的错误Long 值,程序正常运行它必须是IntPtr。新的正确代码如下所示。

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

【讨论】:

  • 正如评论中指出的,Long = Integer。你错过了 cch 论点。使用网站。
  • 最大的错误是没有错误检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多