用VB如何编写系统热键程序,网上有很多现成代码,但大都使用了窗口,即使这个窗口根本没有用。其实,如果只是要在某个热键中处理某件事件,根本不需要创建窗口,也无需借助窗口子类化。本文以获得当前IE页面中Body里的HTML文档为例,具体演示了如何编写一个无窗口的系统热键程序,需要说明的是,由于MsgBox函数中字符串的长度限制,可能会显示HTML文档不完整。具体代码如下:
Option Explicit '* ******************************************** * '* 模块名称:test.bas '* 功能:演示如何编写无窗口系统热键, '* 并在热键中获得当前IE页面内容。 '* 作者:lyserver '* 联系方式:http://blog.csdn.net/lyserver '* ******************************************** * Private Declare Function RegisterHotKey Lib "user32" (ByVal hWnd As Long,ByVal id As Long,ByVal fskey_Modifiers As Long,ByVal vk As Long) As Long Private Declare Function UnregisterHotKey Lib "user32" (ByVal hWnd As Long,ByVal id As Long) As Long Const MOD_ALT = &H1 Const MOD_CONTROL = &H2 Private Type MSG hWnd As Long message As Long wParam As Long lParam As Long time As Long pt As Currency End Type Private Declare Function PeekMessage Lib "user32" Alias "PeekMessageA" (lpMsg As MSG,ByVal hWnd As Long,ByVal wMsgFilterMin As Long,ByVal wMsgFilterMax As Long,ByVal wRemoveMsg As Long) As Long Private Const PM_REMOVE = &H1 Private Const WM_HOTKEY = &H312 Private Declare Function GetForegroundWindow Lib "user32" () As Long Sub Main() Dim uMsg As MSG Dim hIE As Long Dim objShell As Object,objWin As Object RegisterHotKey 0,1,MOD_CONTROL,Asc("g") RegisterHotKey 0,2,Asc("G") RegisterHotKey 0,3,MOD_CONTROL Or MOD_ALT,Asc("q") RegisterHotKey 0,4,Asc("Q") Do PeekMessage uMsg,PM_REMOVE If uMsg.message = WM_HOTKEY Then If uMsg.wParam = 1 Or uMsg.wParam = 2 Then hIE = GetForegroundWindow() Set objShell = CreateObject("Shell.Application") For Each objWin In objShell.Windows If LCase(Right(objWin.FullName,12)) = "iexplore.exe" And objWin.hWnd = hIE Then MsgBox objWin.document.body.innerHTML,"当前IE窗口页面内容,由于MsgBox限制显示不完整" End If Next ElseIf uMsg.wParam = 3 Or uMsg.wParam= 4 Then Exit Do End If End If DoEvents Loop UnregisterHotKey 0,4 UnregisterHotKey 0,3 UnregisterHotKey 0,2 UnregisterHotKey 0,1 End Sub