【VB】点击控件,窗体不获得焦点

本文为旧博客迁移的文章

首先创建一个Button控件。

upload successful

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Option Explicit
Rem 转移输入焦点的声明
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Rem 禁止本窗体拥有输入焦点的常数
Private Const HWND_NOTOPMOST = -2
Private Const WS_DISABLED = &H8000000
Private Const GWL_EXSTYLE = (-20)
Private Const GWL_STYLE = (-16)

Private Sub Form_Load()
Rem 窗体调用时置顶,且禁止拥有输入焦点
SetWindowLong Me.hwnd, GWL_EXSTYLE, GetWindowLong(Me.hwnd, GWL_EXSTYLE) Or WS_DISABLED

Rem 打开Notepad供测试,并且写入文字
Dim a
a = Shell("notepad.exe", vbNormalFocus)
AppActivate a
SendKeys "请点击窗体的按钮,看看窗体有没有获得焦点", True
End Sub