Форум программистов «Весельчак У»
  *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

  • Рекомендуем проверить настройки временной зоны в вашем профиле (страница "Внешний вид форума", пункт "Часовой пояс:").
  • У нас больше нет рассылок. Если вам приходят письма от наших бывших рассылок mail.ru и subscribe.ru, то знайте, что это не мы рассылаем.
   Начало  
Наши сайты
Помощь Поиск Календарь Почта Войти Регистрация  
 
Страниц: [1]   Вниз
  Печать  
Автор Тема: Перехват нажатия клавиш, если программа свернута в трей  (Прочитано 42710 раз)
0 Пользователей и 2 Гостей смотрят эту тему.
Dimyan
Гость
« : 01-03-2004 14:08 » 

Как мне перехватить нажатие какой либо клавиши моей программкой если она сидит свернутая в трее?
« Последнее редактирование: 24-11-2007 14:06 от Алексей1153++ » Записан
Kuzmich
Гость
« Ответ #1 : 02-03-2004 05:16 » 

подозреваю, что тебе нужен хот-кей, как реализовать незнаю
Записан
Dimyan
Гость
« Ответ #2 : 02-03-2004 09:06 » 

я даже больше подозреваю, что видимо в C# ничего подобного нет и придется использовать системный хук, НО КАК???   Так больше нельзя...
Записан
Dimyan
Гость
« Ответ #3 : 03-03-2004 13:16 » 

Ребятки, ну очень надо, ну подскажите кто-нибудь, ниужто ни кто не знает  Так больше нельзя...   Так больше нельзя...   Так больше нельзя...
Записан
Serega
Гость
« Ответ #4 : 03-03-2004 18:34 » 

Хук реализовать не так уж и сложно используюя следующие функции:
SetWindowsHookEx, UnhookWindowsHookEx, и CallNextHookEx

Честно говоря никогда подобного раньше не делал, но сейчас нашел статью, и решил ради интереса написать обработку горячих кнопок, за вечер думаю управлюсь, ночером выложу код
Записан
Serega
Гость
« Ответ #5 : 03-03-2004 18:39 » 

Еще одна интересная статейка, там есть исходник класса для работы с хуками и пример как его использовать для хука мышки
Записан
Serega
Гость
« Ответ #6 : 03-03-2004 21:26 » 

По ходу действия нашел интересную функцию

BOOL RegisterHotKey(HWND hWnd, int id, UINT fsModifiers, UINT vk);

hWnd
[in] Handle to the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL, WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.
id
[in] Specifies the identifier of the hot key. No other hot key in the calling thread should have the same identifier. An application must specify a value in the range 0x0000 through 0xBFFF. A shared dynamic-link library (DLL) must specify a value in the range 0xC000 through 0xFFFF (the range returned by the GlobalAddAtom function). To avoid conflicts with hot-key identifiers defined by other shared DLLs, a DLL should use the GlobalAddAtom function to obtain the hot-key identifier.
fsModifiers
[in] Specifies keys that must be pressed in combination with the key specified by the uVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.
MOD_ALT
Either ALT key must be held down.
MOD_CONTROL
Either CTRL key must be held down.
MOD_SHIFT
Either SHIFT key must be held down.
MOD_WIN
Either WINDOWS key was held down. These keys are labeled with the Microsoft® Windows® logo.
vk
[in] Specifies the virtual-key code of the hot key.
Return Value

If the function succeeds, the return value is nonzero.
Записан
Serega
Гость
« Ответ #7 : 03-03-2004 22:15 » 

Вот что получилось
Код:
using System;
using System.Runtime.InteropServices;

namespace Microsoft.Win32
{
#region Keyboard Hook Event Routine

public class KeyboardHookEventArgs
{
public readonly bool alt;
public readonly bool ctrl;
public readonly bool shift;
public readonly string character;

public KeyboardHookEventArgs(string character, bool alt, bool ctrl, bool shift)
{
this.character = character;
this.alt = alt;
this.ctrl = ctrl;
this.shift = shift;
}
}

public delegate void KeyboardHookEventHandler(object sender, KeyboardHookEventArgs e);

#endregion

public class KeyboardHook : LocalWindowsHook, IDisposable
{
#region Construction

public KeyboardHook() : base( HookType.WH_KEYBOARD )
{
this.HookInvoked += new HookEventHandler(this.KeyboardHookInvoked);
}

#endregion

#region Disposing

~KeyboardHook() | Dispose( false ); }

protected void Dispose( bool disposing )
{
if( IsInstalled ) Uninstall();
if( disposing ) GC.SuppressFinalize( this );
}

public void Dispose() | Dispose( true ); }

#endregion

#region Events

public event KeyboardHookEventHandler KeyPressed;

protected void OnKeyPressed(KeyboardHookEventArgs e)
{
if( KeyPressed != null ) KeyPressed(this, e);
}

#endregion

#region Keyboard Hook specific code

enum VKCodes
{
CONTROL = 0x11,
ALT = 0x12,
SHIFT = 0xA0,
}

private void KeyboardHookInvoked(object sender, HookEventArgs e)
{
bool alt = GetAsyncKeyState((int)VKCodes.ALT) != 0;
bool ctrl = GetAsyncKeyState((int)VKCodes.CONTROL) != 0;
bool shift = GetAsyncKeyState((int)VKCodes.SHIFT) != 0;
string str = " };
GetKeyNameText(e.lParam, str, 2);
OnKeyPressed(new KeyboardHookEventArgs(str, alt, ctrl, shift));
}

#endregion

#region Win32 Imports

[DllImport("user32.dll")]
static extern short GetAsyncKeyState(int vKey);

[DllImport("user32.dll")]
static extern int GetKeyNameText(IntPtr lParam, [MarshalAs(UnmanagedType.LPWStr)] string pString, int nSize);

#endregion
}
}
Тут я использовал класс LocalWindowsHook из этого примера
« Последнее редактирование: 24-11-2007 13:53 от Алексей1153++ » Записан
Serega
Гость
« Ответ #8 : 03-03-2004 22:25 » 

С помощью подобного кода можно узнать какую комбинацию клавиш нажал пользователь и вызвать RegisterHotKey
А как обработать WM_HOTKEY в своем окне ?
а точнее как установить обработчик для любого нужного мне сообщения ?
Записан
Dimyan
Гость
« Ответ #9 : 04-03-2004 06:25 » 

а что за класс LocalWindowsHook?
у меня пишет что такой тип или пространство имен не найдено Жаль
и то же самое с HookEventArgs в
Код:
private void KeyboardHookInvoked(object sender, HookEventArgs e)
« Последнее редактирование: 24-11-2007 13:54 от Алексей1153++ » Записан
Dimyan
Гость
« Ответ #10 : 04-03-2004 06:31 » 

если я правильно понял то HookEventArgs это впаправде KeyboardHookEventArgs ?
Записан
Serega
Гость
« Ответ #11 : 04-03-2004 08:07 » 

Нет не так, это аргумент для события KeyPressed, надо по другому назвать
А на класс LocalWindowsHook я дал ссылку

Вот весь код
Хук для клавы
Код:
using System;
using System.Runtime.InteropServices;

namespace Microsoft.Win32
{
#region Keyboard Hook Events Routine

public class KeyPressedEventArgs
{
public readonly bool alt;
public readonly bool ctrl;
public readonly bool shift;
public readonly string character;

public KeyPressedEventArgs(string character, bool alt, bool ctrl, bool shift)
{
this.character = character;
this.alt = alt;
this.ctrl = ctrl;
this.shift = shift;
}
}

public delegate void KeyPressedEventHandler(object sender, KeyPressedEventArgs e);

#endregion

public class KeyboardHook : LocalWindowsHook, IDisposable
{
#region Construction

public KeyboardHook() : base( HookType.WH_KEYBOARD )
{
this.HookInvoked += new HookEventHandler(this.KeyboardHookInvoked);
}

#endregion

#region Disposing

~KeyboardHook() | Dispose( false ); }

protected void Dispose( bool disposing )
{
if( IsInstalled ) Uninstall();
if( disposing ) GC.SuppressFinalize( this );
}

public void Dispose() | Dispose( true ); }

#endregion

#region Events

public event KeyPressedEventHandler KeyPressed;

protected void OnKeyPressed(KeyPressedEventArgs e)
{
if( KeyPressed != null ) KeyPressed(this, e);
}

#endregion

#region Keyboard Hook specific code

enum VKCodes
{
CONTROL = 0x11,
ALT = 0x12,
SHIFT = 0xA0,
}

private void KeyboardHookInvoked(object sender, HookEventArgs e)
{
bool alt = GetAsyncKeyState((int)VKCodes.ALT) != 0;
bool ctrl = GetAsyncKeyState((int)VKCodes.CONTROL) != 0;
bool shift = GetAsyncKeyState((int)VKCodes.SHIFT) != 0;
string str = " };
GetKeyNameText(e.lParam, str, str.Length + 1);
OnKeyPressed(new KeyPressedEventArgs(str, alt, ctrl, shift));
}

#endregion

#region Win32 Imports

[DllImport("user32.dll")]
static extern short GetAsyncKeyState(int vKey);

[DllImport("user32.dll")]
static extern int GetKeyNameText(IntPtr lParam, [MarshalAs(UnmanagedType.LPWStr)] string pString, int nSize);

#endregion
}
}
Класс для работы с хуками
Код:
// ***********************************************************************
//  LocalWindowsHook class
//  Dino Esposito, summer 2002
//
//  Provide a general infrastructure for using Win32
//  hooks in .NET applications
//
// ***********************************************************************

//
// I took this class from the example at http://msdn.microsoft.com/msdnmag/issues/02/10/cuttingedge
// and made a couple of minor tweaks to it - dpk
//

using System;
using System.Runtime.InteropServices;

namespace Microsoft.Win32
{
#region Class HookEventArgs
public class HookEventArgs : EventArgs
{
public int HookCode; // Hook code
public IntPtr wParam; // WPARAM argument
public IntPtr lParam; // LPARAM argument
}
#endregion

#region Enum HookType
// Hook Types
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
#endregion

#region Class LocalWindowsHook
public class LocalWindowsHook
{
// ************************************************************************
// Filter function delegate
public delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
// ************************************************************************

// ************************************************************************
// Internal properties
protected IntPtr m_hhook = IntPtr.Zero;
protected HookProc m_filterFunc = null;
protected HookType m_hookType;
// ************************************************************************

// ************************************************************************
// Event delegate
public delegate void HookEventHandler(object sender, HookEventArgs e);
// ************************************************************************

// ************************************************************************
// Event: HookInvoked
public event HookEventHandler HookInvoked;
protected void OnHookInvoked(HookEventArgs e)
{
if (HookInvoked != null)
HookInvoked(this, e);
}
// ************************************************************************

// ************************************************************************
// Class constructor(s)
public LocalWindowsHook(HookType hook)
{
m_hookType = hook;
m_filterFunc = new HookProc(this.CoreHookProc);
}
public LocalWindowsHook(HookType hook, HookProc func)
{
m_hookType = hook;
m_filterFunc = func;
}
// ************************************************************************

// ************************************************************************
// Default filter function
protected int CoreHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
return CallNextHookEx(m_hhook, code, wParam, lParam);

// Let clients determine what to do
HookEventArgs e = new HookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;
OnHookInvoked(e);

// Yield to the next hook in the chain
return CallNextHookEx(m_hhook, code, wParam, lParam);
}
// ************************************************************************

// ************************************************************************
// Install the hook
public void Install()
{
m_hhook = SetWindowsHookEx(
m_hookType,
m_filterFunc,
IntPtr.Zero,
(int) AppDomain.GetCurrentThreadId());
}
// ************************************************************************

// ************************************************************************
// Uninstall the hook
public void Uninstall()
{
UnhookWindowsHookEx(m_hhook);
m_hhook = IntPtr.Zero;
}
// ************************************************************************

public bool IsInstalled
{
get| return m_hhook != IntPtr.Zero; }
}

#region Win32 Imports
// ************************************************************************
// Win32: SetWindowsHookEx()
[DllImport("user32.dll")]
protected static extern IntPtr SetWindowsHookEx(HookType code,
HookProc func,
IntPtr hInstance,
int threadID);
// ************************************************************************

// ************************************************************************
// Win32: UnhookWindowsHookEx()
[DllImport("user32.dll")]
protected static extern int UnhookWindowsHookEx(IntPtr hhook);
// ************************************************************************

// ************************************************************************
// Win32: CallNextHookEx()
[DllImport("user32.dll")]
protected static extern int CallNextHookEx(IntPtr hhook,
int code, IntPtr wParam, IntPtr lParam);
// ************************************************************************
#endregion
}
#endregion
}
И форма для теста
Код:
using System;
using System.Windows.Forms;
using System.Text;

namespace Microsoft.Win32
{
public class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TextBox textBox1;
private KeyboardHook hook = new KeyboardHook();

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

public Form1()
{
InitializeComponent();
hook.Install();
hook.KeyPressed += new KeyPressedEventHandler(KeyboardHandler);
}

void KeyboardHandler(object sender, KeyPressedEventArgs e)
{
StringBuilder str = new StringBuilder();
if( e.ctrl ) str.Append("CTRL + ");
if( e.alt ) str.Append("ALT + ");
if( e.shift ) str.Append("SHIFT + ");
str.Append(e.character);
textBox1.Text = str.ToString();
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
this.textBox1.Location = new System.Drawing.Point(8, 8);
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(168, 20);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(184, 36);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
}
}
« Последнее редактирование: 24-11-2007 13:57 от Алексей1153++ » Записан
Dimyan
Гость
« Ответ #12 : 04-03-2004 09:16 » 

Все работает, но проблема не решилась, ведь хук должен отлавливать сообщения глобально (или я не прав?), если эту программы свернуть то никакого отслеживания клавиатуры не происходит, а мне изначально надо как таз это, т.е чтоб программа сидя в трее отлавила нажатие определенной клавиши или комбинации.
или я опять чето не допонимаю  Так больше нельзя...
Записан
Serega
Гость
« Ответ #13 : 04-03-2004 11:22 » new

Для этого воспользуемся функцией RegisterHotKey, только я пока не знаю как установить свой обработчик для определенного сообщения (в нашем случае WM_HOTKEY)
Записан
Dimyan
Гость
« Ответ #14 : 04-03-2004 12:27 » 

Тут тоже кое что есть но это все тоже что было выше Жаль
Ищу обработку WM_HOTKEY средствами .Net, пока безрезультатно Жаль
Записан
Serega
Гость
« Ответ #15 : 04-03-2004 13:22 » 

А у меня получилось !!! Отлично

немного изменил KeyPressedEventArgs и код KeyboardHookInvoked
Код:
public class KeyPressedEventArgs : EventArgs
{
public readonly bool alt;
public readonly bool ctrl;
public readonly bool shift;
public readonly string character;
public readonly uint vk;

public KeyPressedEventArgs(string character, bool alt, bool ctrl, bool shift, uint vk)
{
this.character = character;
this.alt = alt;
this.ctrl = ctrl;
this.shift = shift;
this.vk = vk;
}
}

private void KeyboardHookInvoked(object sender, HookEventArgs e)
{
bool alt = GetAsyncKeyState((int)VKCodes.ALT) != 0;
bool ctrl = GetAsyncKeyState((int)VKCodes.CONTROL) != 0;
bool shift = GetAsyncKeyState((int)VKCodes.SHIFT) != 0;
string str = " ";
GetKeyNameText(e.lParam, str, str.Length + 1);
OnKeyPressed(new KeyPressedEventArgs(str, alt, ctrl, shift, (uint)e.wParam));
}
и код формы
Код:
using System;
using System.Windows.Forms;
using System.Text;
using System.Runtime.InteropServices;

namespace Microsoft.Win32
{
public class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button1;
private KeyboardHook hook = new KeyboardHook();

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

KeyPressedEventArgs args;

void KeyboardHandler(object sender, KeyPressedEventArgs e)
{
args = e;
StringBuilder str = new StringBuilder();
if( e.ctrl ) str.Append("CTRL + ");
if( e.alt ) str.Append("ALT + ");
if( e.shift ) str.Append("SHIFT + ");
str.Append(e.character);
textBox1.Text = str.ToString();
}

static int WM_HOTKEY = 0x0312;

protected override void WndProc(ref Message m)
{
if( m.HWnd == this.Handle && m.Msg == WM_HOTKEY )
{
MessageBox.Show("HotKey!!!");
}
base.WndProc(ref m);
}

#region Construction
public Form1()
{
InitializeComponent();
hook.Install();
hook.KeyPressed += new KeyPressedEventHandler(KeyboardHandler);
}
#endregion

#region Disposing
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion

#region Windows Form Designer generated code
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(8, 8);
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(168, 20);
this.textBox1.TabIndex = 0;
this.textBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(184, 8);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(48, 20);
this.button1.TabIndex = 1;
this.button1.Text = "SET";
this.button1.Click += new System.EventHandler(this.OnAddHotKey);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(240, 37);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);

}
#endregion

static int HotKeyID = 1;
static uint MOD_ALT = 0x0001;
static uint MOD_CONTROL = 0x0002;
static uint MOD_SHIFT = 0x0004;

private void OnAddHotKey(object sender, System.EventArgs e)
{
UnregisterHotKey(this.Handle, HotKeyID);
uint Modifiers = 0;
if( args.alt ) Modifiers += MOD_ALT;
if( args.ctrl ) Modifiers += MOD_CONTROL;
if( args.shift ) Modifiers += MOD_SHIFT;
RegisterHotKey(this.Handle, HotKeyID, Modifiers, args.vk);
}

[DllImport("user32.dll")]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

[DllImport("user32.dll")]
static extern bool UnregisterHotKey(IntPtr hWnd,int id);
}
}
работает следующим образом
1. нажимаешь нужное сочетание клавиш и держишь
2. нажимаешь кнопочку "set" на форме и данное сочетание регистрируется как горячая кнопка
3. нажимаешь еше раз это сочетание и вызывается обработчик (messagebox вылазит)
« Последнее редактирование: 24-11-2007 14:01 от Алексей1153++ » Записан
Dimyan
Гость
« Ответ #16 : 04-03-2004 13:30 » 

Serega, молодец  Ага
я уже с работы ухожу, завтра проверю
Так что куча эмоций и благодарностей завтра Ага  Отлично
Записан
Serega
Гость
« Ответ #17 : 04-03-2004 13:30 » 

Код пока кривоват, но это работает
если есть желание то можно написать либу для хот-кеев
Записан
Dimyan
Гость
« Ответ #18 : 05-03-2004 06:28 » 

Serega, спосибо огромное, все работает как надо (вроде Ага)
Записан
Dimyan
Гость
« Ответ #19 : 05-03-2004 06:50 » 

Вот тока я чет понять не могу, вчера весь вечер потратил на изучение хуков (есна вся инфа по WinAPI) и везде написано приблизительно следующие:
"Чтобы создать глобальный системный хук, его код нужно поместить в DLL, призапуске программы эта DLL будет помещена в память (вроде как в определенную область) и будет сканировать необходимые сообщения даже если программа не активна. Хук помещенный к код программы может работать только как локальный, т.е. только в треде непосредственно самой программы"

Но то что я вижу этому обсалютно противоречет, т.е. я вижу перед собой программу которая прекрастно отлавливает глобальные сообщения клавиатуры, при этом код хука компилируется в общий программный модуль, это как?
и DLL надо всетки или нет?
уф совсем запутался Жаль Улыбаюсь
Записан
Serega
Гость
« Ответ #20 : 05-03-2004 08:28 » 

Вот что написано в мсдн:

The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. You would install a hook procedure to monitor the system for certain types of events. These events are associated either with a specific thread or with all threads in the same desktop as the calling thread.

HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD dwThreadId);

lpfn
[in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
hMod
[in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter. The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by the current process and if the hook procedure is within the code associated with the current process.
dwThreadId
[in] Specifies the identifier of the thread with which the hook procedure is to be associated. If this parameter is zero, the hook procedure is associated with all existing threads running in the same desktop as the calling thread.

Тоесть можно поставить хук для определенного процесса, указав его ID, а можно для рабочего стола, указав хендл DLL
Причем обработчик может быть в нашем процессе только если мы устанавливаем хук для нашего процесса, в остальных случаях нужно использовать DLL

вот код из нашего приложения
Код:
public void Install()
{
m_hhook = SetWindowsHookEx(
m_hookType,
m_filterFunc,
IntPtr.Zero,
(int) AppDomain.GetCurrentThreadId());
}
У нас обработчик только для нашего процесса, поэтому мы не может отлавливать нажатие кнопок глобально с помощью хука.

Чтобы отлавливать нажатие кнопок глобально нужно либо DLL либо зарегистрировать хот-кей (а может и еще есть решения).
DLL я делать не стал.

вот кусок мсдн, по поводу регистрации хот-кеев:

The RegisterHotKey function defines a system-wide hot key.

BOOL RegisterHotKey(HWND hWnd, int id, UINT fsModifiers, UINT vk);

hWnd
[in] Handle to the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL, WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.
id
[in] Specifies the identifier of the hot key. No other hot key in the calling thread should have the same identifier. An application must specify a value in the range 0x0000 through 0xBFFF. A shared dynamic-link library (DLL) must specify a value in the range 0xC000 through 0xFFFF (the range returned by the GlobalAddAtom function). To avoid conflicts with hot-key identifiers defined by other shared DLLs, a DLL should use the GlobalAddAtom function to obtain the hot-key identifier.
fsModifiers
[in] Specifies keys that must be pressed in combination with the key specified by the uVirtKey parameter in order to generate the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.
MOD_ALT
Either ALT key must be held down.
MOD_CONTROL
Either CTRL key must be held down.
MOD_SHIFT
Either SHIFT key must be held down.
MOD_WIN
Either WINDOWS key was held down. These keys are labeled with the Microsoft® Windows® logo.
vk
[in] Specifies the virtual-key code of the hot key.

Принцип работы такой:
- с помощью хука узнаем какую комбинацию кнопок сделать хот-кеем
- регистрируем хот-кей
- обрабатываем нажатие хот-кея
« Последнее редактирование: 24-11-2007 14:04 от Алексей1153++ » Записан
Dimyan
Гость
« Ответ #21 : 05-03-2004 09:02 » 

А мне тут примерчик с  RegisterHotKey подсказали:
Код:
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

 

public class WindowsForm : System.Windows.Forms.Form
{
 [DllImport("USER32.DLL", EntryPoint="RegisterHotKey")]
 public static extern bool HotK(int hWnd, int id, uint fsModifiers, uint vk);
 public static int pressCnt;
 const int MOD_CONTROL = 2;
 const int MOD_ALT = 1;
 const int WM_HOTKEY = 0x312;
 const int VK_F2 = 0x71;
 
 [STAThread]
 public static void Main()
 {
  Application.Run(new WindowsForm());
 }

 public WindowsForm()
 {
  this.Size = new Size(500, 50);
  if( !HotK(this.Handle.ToInt32(), 1, MOD_CONTROL+MOD_ALT, VK_F2) )
   throw( new ArgumentException("Can't install hot key! Bad arguments?"));

 }

 protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_HOTKEY:
   this.Text = "HotKey was pessed "+(++pressCnt).ToString()+" times."+
     "Lparam="+m.LParam.ToInt32().ToString("X")+";Wparam="+m.WParam.ToInt32().ToString("X");
         break;               
  }
        base.WndProc(ref m);
 }
}
« Последнее редактирование: 24-11-2007 14:05 от Алексей1153++ » Записан
Страниц: [1]   Вверх
  Печать  
 

Powered by SMF 1.1.21 | SMF © 2015, Simple Machines