2008年8月6日水曜日

ExcelでCtrl+CとCtrl+VをハンドリングするVBA

Workbook_Open()で、Regist()をCallし、
Workbook_BeforeClose(Cancel As Boolean)で、Unregist()をCallする。




'ウィンドウ情報の設定
Private Declare Function SetWindowLong Lib "user32.dll" Alias "SetWindowLongA" _
(ByVal hWnd As Long, _
ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
'ウィンドウプロシージャのコール
Private Declare Function CallWindowProc Lib "user32.dll" Alias
"CallWindowProcA" _
(ByVal lpPrevWndFunc As Long, _
ByVal hWnd As Long, _
ByVal msg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
'ホットキーを登録する
Private Declare Function RegisterHotKey Lib "user32.dll" _
(ByVal hWnd As Long, _
ByVal id As Long, _
ByVal fsModifiers As Long, _
ByVal vk As Long) As Long
'ホットキーを解除する
Private Declare Function UnregisterHotKey Lib "user32.dll" _
(ByVal hWnd As Long, _
ByVal id As Long) As Long

'定数定義
Private Const GWL_WNDPROC = (-4) 'ウィンドウプロシージャ
Private Const MOD_CONTROL As Integer = &H2 'コントロールキー
Private hOldWndProc As Long 'オリジナルウィンドウプロシージャのハンドル
Private Const WM_HOTKEY = &H312 'ホットキーのウィンドウメッセージ
Private Const HK_EVENT_CTRL_C = &H100 'ホットキー番号1
Private Const HK_EVENT_CTRL_V = &H101 'ホットキー番号2

Public Function WndProc(ByVal hWnd As Long, ByVal msg As Long, ByVal
wParam As Long, ByVal lParam As Long) As Long
If msg = WM_HOTKEY Then
Select Case wParam
Case HK_EVENT_CTRL_C:
MsgBox "Ctrl+Cが押された"
Case HK_EVENT_CTRL_V:
MsgBox "Ctrl+Vが押された"
End Select
End If
'オリジナルプロシージャをコール
WndProc = CallWindowProc(hOldWndProc, hWnd, msg, wParam, lParam)
End Function

Public Sub Regist()
'ホットキーの登録
Call RegisterHotKey(Application.
hWnd, HK_EVENT_CTRL_C, MOD_CONTROL, vbKeyC)
Call RegisterHotKey(Application.hWnd, HK_EVENT_CTRL_V, MOD_CONTROL, vbKeyV)

'ウィンドウプロシージャの変更
hOldWndProc = SetWindowLong(Application.hWnd, GWL_WNDPROC,
AddressOf WndProc)
End Sub

Public Sub Unregist()
'ウィンドウプロシージャを元に戻す
Call SetWindowLong(Application.hWnd, GWL_WNDPROC, hOldWndProc)

'ホットキーの解除
Call UnregisterHotKey(Application.hWnd, HK_EVENT_CTRL_V)
Call UnregisterHotKey(Application.hWnd, HK_EVENT_CTRL_C)
End Sub