Events with static functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cristo4
    New Member
    • Nov 2008
    • 2

    #1

    Events with static functions

    I have a class that is able to detect a global key press. However, I don't seem to be able to create a working event that notifies the Form1 of a global keypress.

    The function "HookCallba ck" is static and for some reason it does work to the point of " MyAKeyWasPresse d(int vkKeyCode)" displaying it's 2 messageboxes but the function in Form1 doesn't get fired and displays no messagebox.

    What do I do wrong? I'm breaking my head on it for days now. Thanks in advance.

    The code in Form1:
    Code:
    ...
            InterceptKeys Hook = new InterceptKeys();
    
            private void Form1_Load(object sender, EventArgs e)
            {
                Hook.MyKeyPressed += new MyOnKeyPressHandler(MyAKeyWasPressed);
             }
    
            private void MyAKeyWasPressed(int vkKeyCode)
            {
                MessageBox.Show("Form1 succesfully received an event from the class!");
                MessageBox.Show(((Keys)vkKeyCode).ToString());
            }

    The code in the class:
    Code:
    ...
    namespace MK
    {
        public delegate void MyOnKeyPressHandler(int KeyCode);
        class InterceptKeys
    {
            public event MyOnKeyPressHandler MyKeyPressed;
    ...
            public InterceptKeys()  // constructor
            {
                MyKeyPressed = new MyOnKeyPressHandler(OnKeyPressed);
            }
            private static void OnKeyPressed(int vkKeyCode)
            {
                MessageBox.Show("The function OnKeyPressed in the class worked! The key I found was: "+((Keys)vkKeyCode).ToString());
            }
            private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
            {
                if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
                {
                    int vkCode = Marshal.ReadInt32(lParam);
                    OnKeyPressed(vkCode);
                }
    
                return CallNextHookEx(_hookID, nCode, wParam, lParam);
            }
    
    ...
    
    }
Working...