PDA

View Full Version : آموزش: كليد ميان بر - Hot Key



robat7
دوشنبه 11 مرداد 1389, 05:12 صبح
سلام
در اين تاپيك نحوه ايجاد كليد ميان بر (براي دسترسي به آيكون هاي Toolbar ) شرح داده مي شود.

namespace هاي مورد نياز در كلاس:


using System.Windows.Forms;
using System.Runtime.InteropServices;

نخست بايد كلاس زير را تعريف نماييم



classHotkeys
{
[DllImport("user32.dll")]
privatestaticexternbool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
privatestaticexternbool UnregisterHotKey(IntPtr hWnd, int id);
privateint modifier;
privateint key;
privateIntPtr hWnd;
privateint id;
publicstaticclassConstants
{
//modifiers
publicconstint NOMOD = 0x0000;
publicconstint ALT = 0x0001;
publicconstint CTRL = 0x0002;
publicconstint SHIFT = 0x0004;
publicconstint WIN = 0x0008;
//windows message id for hotkey
publicconstint WM_HOTKEY_MSG_ID = 0x0312;
}
public Hotkeys(int modifier, Keys key, Form form)
{
this.modifier = modifier;
this.key = (int)key;
this.hWnd = form.Handle;
id = this.GetHashCode();
}
publicoverrideint GetHashCode()
{
return modifier ^ key ^ hWnd.ToInt32();
}
publicbool Register()
{
return RegisterHotKey(hWnd, id, modifier, key);
}
publicbool Unregiser()
{
return UnregisterHotKey(hWnd, id);
}
}



namespace مورد نياز در فرم


using System.Runtime.InteropServices;

سپس متغيرهاي زير را در ابتداي فرم تعريف مي نماييم (براي هر كليد ميانبر يك متغير جدا)


Hotkeys ghk;
Hotkeys ghk1;
Hotkeys ghk2;

سپس در سازنده فرم مورد نظر پس از Initializecomponent() عبارات زير را وارد مي نماييم


InitializeComponent();
ghk = newHotkeys(Hotkeys.Constants.CTRL, Keys.OemSemicolon, this);
ghk1 = newHotkeys(Hotkeys.Constants.CTRL, Keys.M, this);
ghk2 = newHotkeys(Hotkeys.Constants.CTRL, Keys.D, this);


در Form_Load() كليد ها را ثبت مي نماييم


ghk.Register();
ghk1.Register();
ghk2.Register();


و حتما در Form_Close()كليدها را پاك مي نماييم


ghk.Unregiser();
ghk1.Unregiser();
ghk2.Unregiser();


براي كنترل كليدهاي تركيبي وارد شده توسط كاربر روتين هاي زير را در برنامه اضافه نماييد


privateKeys GetKey(IntPtr LParam)
{
return (Keys)((LParam.ToInt32()) >> 16); // not all of the parenthesis are needed, I just found it easier to see what's happening
}
protectedoverridevoid WndProc(refMessage m)
{
if (m.Msg == Hotkeys.Constants.WM_HOTKEY_MSG_ID)
switch (GetKey(m.LParam))
{
caseKeys.OemSemicolon:
your code
break;
caseKeys.M:
your code
break;
caseKeys.D:
your code
break;
}
base.WndProc(ref m);
}


پيروز باشيد
مرجع:
http://www.dreamincode.net/forums/topic/180436-global-hotkeys