Catching the "Home" key press in Smartphone.

You've probably noticed that the "Home" key press is not possible to catch in either of the Key event handles of the Form or Control. The solution to that will be to use the RegisterHotKey API in conjunction with MessageWindow:

using System;

using Microsoft.WindowsCE.Forms;

using System.Windows.Forms;

using System.Runtime.InteropServices;

 

public class MessageWin : MessageWindow

{

    //event for client

    public System.EventHandler HomeKeyPress;

 

    public MessageWin()

    {

       //register to listen for home key

       RegisterHotKey(this.Hwnd, VK_LWIN, 8, VK_LWIN);

    }

 

 

    ~MessageWin()

    {

       Unregister();

    }

 

    protected override void WndProc(ref Message m)

    {

       if (m.Msg == WM_HOTKEY)

       {

          if ((int)m.WParam == VK_LWIN)

             //Raise event

             if (HomeKeyPress!=null)

                   HomeKeyPress(this, null);

       }

       base.WndProc (ref m);

    }

 

  #region P/Invokes

    private const int VK_LWIN    =    0x5B;

    private const int WM_HOTKEY   =      0x0312;

 

   [DllImport("coredll.dll")]

    public static extern bool RegisterHotKey(

         IntPtr hWnd, // handle to window

         int id, // hot key identifier

         int Modifiers, // key-modifier options

         int key //virtual-key code);

 

   [DllImport("coredll.dll")]

    public static extern bool UnregisterHotKey(

         IntPtr      hWnd,

         int         id);

   #endregion

 }

The usage of this class should be pretty obviouse:

MessageWin  msgWin = new MessageWin();

msgWin.HomeKeyPress+=new EventHandler(msgWin_HomeKeyPress);

 

private void msgWin_HomeKeyPress(object sender, System.EventArgs e)

{

      MessageBox.Show("Home Key Pressed.");

}

 You don't need to use this code for catching 'Back' button. The simple KeyPress event would do the job:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
char chBack = Convert.ToChar(27);

if (e.KeyChar == chBack)//back key
{
// process the back key

}

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章