powered by simpleCommunicator - 2.0.53     © 2025 Programmizd 02
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
7 сообщений из 7, страница 1 из 1
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37897244
Игорь1973
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Добрый день.

При установленной английской раскладке клавиатуры и копировании-вставке русского текста через буфер обмена вставляются вопросы.
Я хочу перехватить нажатие горячих клавиш Ctrl+С или Ctrl+X, программно переключить раскладку на русскую и затем повторно копировать выделенный текст в буфер обмена.
Удастся ли такая реализация?
И конкретно - как перехватить нажатие этой комбинации клавиш в любой форме VB6-проекта?

Заранее спасибо.
...
Рейтинг: 0 / 0
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37897368
Фотография Shocker.Pro
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
а в какой винде это требуется?
...
Рейтинг: 0 / 0
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37897392
Фотография Shocker.Pro
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Игорь1973перехватить нажатие горячих клавиш Ctrl+С или Ctrl+Xи, обращаю внимание, что копирование в буфер делается также клавишами Ctrl+Ins, а также контекстным меню мыши.

Вот тут немножко обсуждали.
...
Рейтинг: 0 / 0
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37898217
Фотография VladConn
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Игорь1973Добрый день.

При установленной английской раскладке клавиатуры и копировании-вставке русского текста через буфер обмена вставляются вопросы.
Я хочу перехватить нажатие горячих клавиш Ctrl+С или Ctrl+X, программно переключить раскладку на русскую и затем повторно копировать выделенный текст в буфер обмена.
Удастся ли такая реализация?
И конкретно - как перехватить нажатие этой комбинации клавиш в любой форме VB6-проекта?

Заранее спасибо.

KeyPreview?
...
Рейтинг: 0 / 0
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37898893
Игорь1973
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Спасибо за ответы.
Сторонний контрол, отслеживающий буфер обмена по таймеру, это, конечно, вариант, но
все-таки - как отследить гблобальное нажатие клавиш на клавиатуре (Ctrl+C, Ctrl+X, Ctrl+Ins)?
В любом месте программы (какая бы активная форма программы ни была...).
Есть ли способ? Посредством какой-то Win32 API-функции, думаю, это должно быть возможно.
...
Рейтинг: 0 / 0
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37898920
Фотография Konst_One
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
261.
262.
263.
264.
265.
266.
267.
268.
269.
270.
271.
272.
273.
274.
275.
276.
277.
278.
279.
280.
281.
282.
283.
284.
285.
286.
287.
288.
289.
290.
291.
292.
293.
294.
295.
296.
297.
298.
299.
300.
301.
302.
303.
304.
305.
306.
'**************************************
'Windows API/Global Declarations for :Sy
'     stem-wide mouse and keyboard hook
'**************************************
'See bas module code
'**************************************
' Name: System-wide mouse and keyboard h
'     ook
' Description:Set system-wide mouse and 
'     keyboard hook and generate 'standard' VB
'     events (System_MouseUp/Down/Move, System
'     _KeyUp/Down) with standard parameters (B
'     utton, Shift, X, Y, KeyCode).
' By: Ark
'
'
' Inputs:Form to receive hook notificati
'     on and hook flags
'
' Returns:Mouse/keyboard events with app
'     ropriate parameters
'
'Assumes:Though MSDN says that WH_JOURNA
'     LRECORD hook is thread defined, in w95/9
'     8 it allow system-wide hook when set Thr
'     eadID parameter of hook = 0. To run this
'     code you need form with two multiline te
'     xtboxes (Text1 and Text2) and one label 
'     (Label1).
'
'Side Effects:Works only with w95/98. Do
'     n't work with NT/2000. 
This code use hook, don't stop sample from IDE, use Form [x] button.
'This code is copyrighted and has limite
'     d warranties.
'Please see http://www.Planet-Source-Cod
'     e.com/xq/ASP/txtCodeId.9758/lngWId.1/qx/
'     vb/scripts/ShowCode.htm
'for details.
'**************************************

'---Bas module code---
Option Explicit


Public Enum HookFlags
    HFMouseDown = 1
    HFMouseUp = 2
    HFMouseMove = 4
    HFKeyDown = 8
    HFKeyUp = 16
End Enum


Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long


Private Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long


Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long


Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpDest As Any, lpSource As Any, ByVal cBytes As Long)


Private Declare Function GetAsyncKeyState% Lib "user32" (ByVal vKey As Long)


Private Declare Function GetForegroundWindow& Lib "user32" ()


Private Declare Function GetWindowThreadProcessId& Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long)


Private Declare Function GetKeyboardLayout& Lib "user32" (ByVal dwLayout As Long)


Private Declare Function MapVirtualKeyEx Lib "user32" Alias "MapVirtualKeyExA" (ByVal uCode As Long, ByVal uMapType As Long, ByVal dwhkl As Long) As Long


Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
    Private Const SWP_NOSIZE = &H1
    Private Const SWP_NOMOVE = &H2
    Private Const SWP_NOREDRAW = &H8
    Private Const WM_KEYDOWN = &H100
    Private Const WM_KEYUP = &H101
    Private Const WM_MOUSEMOVE = &H200
    Private Const WM_LBUTTONDOWN = &H201
    Private Const WM_LBUTTONUP = &H202
    Private Const WM_LBUTTONDBLCLK = &H203
    Private Const WM_RBUTTONDOWN = &H204
    Private Const WM_RBUTTONUP = &H205
    Private Const WM_RBUTTONDBLCLK = &H206
    Private Const WM_MBUTTONDOWN = &H207
    Private Const WM_MBUTTONUP = &H208
    Private Const WM_MBUTTONDBLCLK = &H209
    Private Const WM_MOUSEWHEEL = &H20A
    Private Const WH_JOURNALRECORD = 0


Type EVENTMSG
    wMsg As Long
    lParamLow As Long
    lParamHigh As Long
    ' msgTime As Long
    ' hWndMsg As Long
    End Type
    Dim EMSG As EVENTMSG
    Dim hHook As Long, frmHooked As Form, hFlags As Long


Public Function HookProc(ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long


    If nCode < 0 Then
        HookProc = CallNextHookEx(hHook, nCode, wParam, lParam)
        Exit Function
    End If
    Dim i%, j%, k%
    CopyMemory EMSG, ByVal lParam, Len(EMSG)


    Select Case EMSG.wMsg
        Case WM_KEYDOWN


        If (hFlags And HFKeyDown) = HFKeyDown Then
            If GetAsyncKeyState(vbKeyShift) Then j = 1
            If GetAsyncKeyState(vbKeyControl) Then j = 2
            If GetAsyncKeyState(vbKeyMenu) Then j = 4


            Select Case (EMSG.lParamLow And &HFF)
                Case 0 To 31, 90 To 159
                k = (EMSG.lParamLow And &HFF)
                Case Else
                k = MapVirtualKeyEx(EMSG.lParamLow And &HFF, 2, GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow, 0)))
            End Select
        frmHooked.System_KeyDown k, j
    End If
    Case WM_KEYUP


    If (hFlags And HFKeyUp) = HFKeyUp Then
        If GetAsyncKeyState(vbKeyShift) Then j = 1
        If GetAsyncKeyState(vbKeyControl) Then j = 2
        If GetAsyncKeyState(vbKeyMenu) Then j = 4


        Select Case (EMSG.lParamLow And &HFF)
            Case 0 To 31, 90 To 159
            k = (EMSG.lParamLow And &HFF)
            Case Else
            k = MapVirtualKeyEx(EMSG.lParamLow And &HFF, 2, GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow, 0)))
        End Select
    frmHooked.System_KeyUp k, j
End If
Case WM_MOUSEWHEEL
Debug.Print "MouseWheel"
Case WM_MOUSEMOVE


If (hFlags And HFMouseMove) = HFMouseMove Then
    If GetAsyncKeyState(vbKeyLButton) Then i = 1
    If GetAsyncKeyState(vbKeyRButton) Then i = 2
    If GetAsyncKeyState(vbKeyMButton) Then i = 4
    If GetAsyncKeyState(vbKeyShift) Then j = 1
    If GetAsyncKeyState(vbKeyControl) Then j = 2
    If GetAsyncKeyState(vbKeyMenu) Then j = 4
    frmHooked.System_MouseMove i, j, CSng(EMSG.lParamLow), CSng(EMSG.lParamHigh)
End If
Case WM_LBUTTONDOWN, WM_RBUTTONDOWN, WM_MBUTTONDOWN


If (hFlags And HFMouseDown) = HFMouseDown Then
    If GetAsyncKeyState(vbKeyShift) Then i = 1
    If GetAsyncKeyState(vbKeyControl) Then i = 2
    If GetAsyncKeyState(vbKeyMenu) Then i = 4
    frmHooked.System_MouseDown 2 ^ ((EMSG.wMsg - 513) / 3), i, CSng(EMSG.lParamLow), CSng(EMSG.lParamHigh)
End If
Case WM_LBUTTONUP, WM_RBUTTONUP, WM_MBUTTONUP


If (hFlags And HFMouseUp) = HFMouseUp Then
    If GetAsyncKeyState(vbKeyShift) Then i = 1
    If GetAsyncKeyState(vbKeyControl) Then i = 2
    If GetAsyncKeyState(vbKeyMenu) Then i = 4
    frmHooked.System_MouseUp 2 ^ ((EMSG.wMsg - 514) / 3), i, CSng(EMSG.lParamLow), CSng(EMSG.lParamHigh)
End If
End Select
Call CallNextHookEx(hHook, nCode, wParam, lParam)
End Function


Public Sub SetHook(fOwner As Form, flags As HookFlags)
    hHook = SetWindowsHookEx(WH_JOURNALRECORD, AddressOf HookProc, 0, 0)
    Set frmHooked = fOwner
    hFlags = flags
    Window_SetAlwaysOnTop frmHooked.hwnd, True
End Sub


Public Sub RemoveHook()
    UnhookWindowsHookEx hHook
    Window_SetAlwaysOnTop frmHooked.hwnd, False
    Set frmHooked = Nothing
End Sub


Private Function Window_SetAlwaysOnTop(hwnd As Long, bAlwaysOnTop As Boolean) As Boolean
    Window_SetAlwaysOnTop = SetWindowPos(hwnd, -2 - bAlwaysOnTop, 0, 0, 0, 0, SWP_NOREDRAW Or SWP_NOSIZE Or SWP_NOMOVE)
End Function
'---End of bas module code---
'---------------------------------------
'     -----
'---Form code---
'Add two multiline TextBoxes (better wit
'     h vertical scrollbar) and one Label at f
'     orm


Private Sub Form_Load()
    SetHook Me, HFMouseDown + HFMouseUp + HFMouseMove + HFKeyDown + HFKeyUp
    Text1 = "Mouse activity log:"
    Text2 = "Keyboard activity log:"
End Sub


Public Sub System_KeyDown(KeyCode As Integer, Shift As Integer)
    Dim s As String


    Select Case KeyCode
        Case 32 To 90, 160 To 255
        s = LCase(Chr$(KeyCode))
        Case Else
        s = "ASCII code " & KeyCode
    End Select
If Shift = vbShiftMask Then s = UCase(s): s = s & " + Shift "
If Shift = vbCtrlMask Then s = s & " + Ctrl "
If Shift = vbAltMask Then s = s & " + Alt "
Text2 = Text2 & vbCrLf & s & " down"
End Sub


Public Sub System_KeyUp(KeyCode As Integer, Shift As Integer)
    Dim s As String


    Select Case KeyCode
        Case 32 To 90, 160 To 255
        s = LCase(Chr$(KeyCode))
        Case Else
        s = "ASCII code " & KeyCode
    End Select
If Shift = vbShiftMask Then s = UCase(s): s = s & " + Shift "
If Shift = vbCtrlMask Then s = s & " + Ctrl "
If Shift = vbAltMask Then s = s & " + Alt "
Text2 = Text2 & vbCrLf & s & " up"
End Sub


Public Sub System_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
    Dim s As String
    If Button = vbLeftButton Then s = "Left Button "
    If Button = vbRightButton Then s = "Right Button "
    If Button = vbMiddleButton Then s = "Middle Button "
    If Shift = vbShiftMask Then s = s & "+ Shift "
    If Shift = vbCtrlMask Then s = s & "+ Ctrl "
    If Shift = vbAltMask Then s = s & "+ Alt "
    Text1 = Text1 & vbCrLf & s & "Down at pos (pixels): " & CStr(x) & " , " & CStr(y)
End Sub


Public Sub System_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single)
    Dim s As String
    If Button = vbLeftButton Then s = "Left Button "
    If Button = vbRightButton Then s = "Right Button "
    If Button = vbMiddleButton Then s = "Middle Button "
    If Shift = vbShiftMask Then s = s & "+ Shift "
    If Shift = vbCtrlMask Then s = s & "+ Ctrl "
    If Shift = vbAltMask Then s = s & "+ Alt "
    Text1 = Text1 & vbCrLf & s & "Up at pos (pixels): " & CStr(x) & " , " & CStr(y)
End Sub


Public Sub System_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single)
    Dim s As String
    If Button = vbLeftButton Then s = "Left Button "
    If Button = vbRightButton Then s = "Right Button "
    If Button = vbMiddleButton Then s = "Middle Button "
    If Shift = vbShiftMask Then s = s & "+ Shift "
    If Shift = vbCtrlMask Then s = s & "+ Ctrl "
    If Shift = vbAltMask Then s = s & "+ Alt "
    Label1 = "Mouse info" & vbCrLf & "X = " & x & " Y= " & y & vbCrLf
    If s <> "" Then Label1 = Label1 & "Extra Info: " & vbCrLf & s & "pressed"
End Sub


Private Sub Form_Unload(Cancel As Integer)
    RemoveHook
End Sub
'--End of form code--

		



надо проверять, может на новых версиях винды и не заработать
...
Рейтинг: 0 / 0
Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
    #37899076
Игорь1973
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Что-то довольно очень сложновато получается.
Наверное, лучше для каждой формы проставить KeyPreview в True и обрабатывать событие универсальным обработчиком.
Спасибо.
...
Рейтинг: 0 / 0
7 сообщений из 7, страница 1 из 1
Форумы / Visual Basic [игнор отключен] [закрыт для гостей] / Как перехватить глобальное нажатие клавиш Ctrl+C в любой форме?
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]