如果声明不在vb6中工作

时间:2015-06-22 19:27:02

标签: winapi vb6

我想创建一个程序,可以在vb6中关闭一个标题为“Personalization”的窗口。问题是if语句不起作用。这是我的代码(它只找到一个名为“Personalization”的窗口而不关闭它):

Option Explicit

Private Sub Command1_Click()
    Timer1.Enabled = Not Timer1.Enabled
End Sub

Private Sub Timer1_Timer()
    Dim hwnd As Long, lenght As Long
    Dim title As String

    hwnd = GetForegroundWindow

    lenght = GetWindowTextLength(hwnd)
    title = Space$(lenght + 1)
    GetWindowText hwnd, title, lenght + 1

    title = Mid(title, 1, lenght + 1)

    t.Text = title
    t.SelStart = Len(t.Text)
    If title = "Personalization" Then End

End Sub

最后一个条件不起作用,虽然我点击了“个性化”窗口,我可以在文本框中看到它的标题。

以下是if语句的工作原理:

if t.text="Personalization" then end

那么为什么它不能在第一个例子中使用if语句呢?抱歉我的错误(这不是我原来的语言)。

1 个答案:

答案 0 :(得分:1)

您的Mid()声明错误。第三个参数需要length - 1而不是length + 1来剥离空终止符:

title = Mid(title, 1, length - 1)

由于您没有剥离空终止符,因此title变量实际上并不包含"Personalization",因此您的比较失败。您的文本框显示正确,因为分配Text属性最终会导致文本框收到WM_SETTEXT消息,该消息将以空终止字符串作为输入,因此将忽略任何额外的空值。

更好的选择是使用GetWindowText()的返回值,即复制到title中的 true 长度减去空终止符:

Private Sub Timer1_Timer()
    Dim hwnd As Long, lenght As Long
    Dim title As String

    hwnd = GetForegroundWindow

    lenght = GetWindowTextLength(hwnd) + 1
    title = Space$(lenght)
    lenght = GetWindowText(hwnd, title, lenght)

    title = Mid(title, 1, lenght)

    t.Text = title
    t.SelStart = Len(t.Text)
    If title = "Personalization" Then
      ' ...
    End If

End Sub