Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. I'm becoming crazy about keys

I'm becoming crazy about keys

Scheduled Pinned Locked Moved C#
csharphelpquestion
14 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Anonymous
    wrote on last edited by
    #1

    Did someone get a successfull way to register hotkeys in C# ? eg : CONTROL + SHIFT + J or whatever else which works whoever has the focus. [DllImport("user32.dll")] private static extern bool RegisterHotKey(long hWnd, int id, int fsModifiers, int vk); // MOD_CONTROL + MOD_ALT = 6 bool b = RegisterHotKey(GetForegroundWindow(),100,6, 'j'); /*0x4A*/ or 'j' doesn't work. b is always false...No way to register anything. Please help, my program is useless whithout hotkeys. Thanks. Nd. PS : MOD_ALT 1 MOD_CONTROL 2 MOD_SHIFT 4 MOD_WIN 8

    L J 2 Replies Last reply
    0
    • A Anonymous

      Did someone get a successfull way to register hotkeys in C# ? eg : CONTROL + SHIFT + J or whatever else which works whoever has the focus. [DllImport("user32.dll")] private static extern bool RegisterHotKey(long hWnd, int id, int fsModifiers, int vk); // MOD_CONTROL + MOD_ALT = 6 bool b = RegisterHotKey(GetForegroundWindow(),100,6, 'j'); /*0x4A*/ or 'j' doesn't work. b is always false...No way to register anything. Please help, my program is useless whithout hotkeys. Thanks. Nd. PS : MOD_ALT 1 MOD_CONTROL 2 MOD_SHIFT 4 MOD_WIN 8

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #2

      Anonymous wrote: [DllImport("user32.dll")] private static extern bool RegisterHotKey(long hWnd, int id, int fsModifiers, int vk); The returned value of the function is a C++ BOOL iow in C# an int, 0 = false all else = true; Maybe this helps :) MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

      N 1 Reply Last reply
      0
      • A Anonymous

        Did someone get a successfull way to register hotkeys in C# ? eg : CONTROL + SHIFT + J or whatever else which works whoever has the focus. [DllImport("user32.dll")] private static extern bool RegisterHotKey(long hWnd, int id, int fsModifiers, int vk); // MOD_CONTROL + MOD_ALT = 6 bool b = RegisterHotKey(GetForegroundWindow(),100,6, 'j'); /*0x4A*/ or 'j' doesn't work. b is always false...No way to register anything. Please help, my program is useless whithout hotkeys. Thanks. Nd. PS : MOD_ALT 1 MOD_CONTROL 2 MOD_SHIFT 4 MOD_WIN 8

        J Offline
        J Offline
        James T Johnson
        wrote on last edited by
        #3

        This works for me First the definitions:

        [DllImport("user32.dll", SetLastError=true)]
        public static extern bool RegisterHotKey(
        IntPtr hWnd, // handle to window
        int id, // hot key identifier
        KeyModifiers fsModifiers, // key-modifier options
        Keys vk // virtual-key code
        );

        [DllImport("user32.dll", SetLastError=true)]
        public static extern bool UnregisterHotKey(
        IntPtr hWnd, // handle to window
        int id // hot key identifier
        );

        [Flags()]
        public enum KeyModifiers
        {
        Alt = 1,
        Control = 2,
        Shift = 4,
        Windows = 8
        }

        Now a sample use of the code: In Form load:

        bool success = RegisterHotKey(Handle, 100,
        KeyModifiers.Control | KeyModifiers.Shift, Keys.J);
        System.Diagnostics.Trace.WriteLine(
        "Success = " + success.ToString());

        In Form closed or closing:

        UnregisterHotKey(Handle, 100);

        And finally override the WndProc so the message can be handled.

        protected override void WndProc( ref Message m )
        {
        const int WM_HOTKEY = 0x0312;

        switch(m.Msg)
        {
        case WM\_HOTKEY:
        	MessageBox.Show("Hotkey pressed");
        	break;
        }
        
        base.WndProc(ref m );
        

        }

        HTH, James "And we are all men; apart from the females." - Colin Davies

        N L 2 Replies Last reply
        0
        • L leppie

          Anonymous wrote: [DllImport("user32.dll")] private static extern bool RegisterHotKey(long hWnd, int id, int fsModifiers, int vk); The returned value of the function is a C++ BOOL iow in C# an int, 0 = false all else = true; Maybe this helps :) MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

          N Offline
          N Offline
          nitro666
          wrote on last edited by
          #4

          Thanks Leppie, I didn't know that. It wasn't working because I wasn't doing the registration with the right handle ! I was using GetForegroundWindow during form init, and at this moment, the handle is pointing to Visual Studio and not the launched application... Nd.

          1 Reply Last reply
          0
          • J James T Johnson

            This works for me First the definitions:

            [DllImport("user32.dll", SetLastError=true)]
            public static extern bool RegisterHotKey(
            IntPtr hWnd, // handle to window
            int id, // hot key identifier
            KeyModifiers fsModifiers, // key-modifier options
            Keys vk // virtual-key code
            );

            [DllImport("user32.dll", SetLastError=true)]
            public static extern bool UnregisterHotKey(
            IntPtr hWnd, // handle to window
            int id // hot key identifier
            );

            [Flags()]
            public enum KeyModifiers
            {
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
            }

            Now a sample use of the code: In Form load:

            bool success = RegisterHotKey(Handle, 100,
            KeyModifiers.Control | KeyModifiers.Shift, Keys.J);
            System.Diagnostics.Trace.WriteLine(
            "Success = " + success.ToString());

            In Form closed or closing:

            UnregisterHotKey(Handle, 100);

            And finally override the WndProc so the message can be handled.

            protected override void WndProc( ref Message m )
            {
            const int WM_HOTKEY = 0x0312;

            switch(m.Msg)
            {
            case WM\_HOTKEY:
            	MessageBox.Show("Hotkey pressed");
            	break;
            }
            
            base.WndProc(ref m );
            

            }

            HTH, James "And we are all men; apart from the females." - Colin Davies

            N Offline
            N Offline
            nitro666
            wrote on last edited by
            #5

            Thanks for your answer and the needed time. I replace all my code by yours and it still didn't work...That give me the idea to search for something else and I got it. I was using GetActiveWindow in order to get the handle of the current program...I know, it's not the best way...I will search for a better one later, time is running. During the init of the form, the GetActiveWindow returns the handle of Visual Studio and not the one of my program. So I was trying to register hotkeys for Visual Studio and it wasn't working. Well, thanks to you it's working fine now, I was gonna give up (too much time spent on it) My program should be ready for tomorrow with minimal features.:) Nd.

            J 1 Reply Last reply
            0
            • N nitro666

              Thanks for your answer and the needed time. I replace all my code by yours and it still didn't work...That give me the idea to search for something else and I got it. I was using GetActiveWindow in order to get the handle of the current program...I know, it's not the best way...I will search for a better one later, time is running. During the init of the form, the GetActiveWindow returns the handle of Visual Studio and not the one of my program. So I was trying to register hotkeys for Visual Studio and it wasn't working. Well, thanks to you it's working fine now, I was gonna give up (too much time spent on it) My program should be ready for tomorrow with minimal features.:) Nd.

              J Offline
              J Offline
              James T Johnson
              wrote on last edited by
              #6

              If you want to get the HWND for your Form use the Handle property of the Form. James "And we are all men; apart from the females." - Colin Davies

              1 Reply Last reply
              0
              • J James T Johnson

                This works for me First the definitions:

                [DllImport("user32.dll", SetLastError=true)]
                public static extern bool RegisterHotKey(
                IntPtr hWnd, // handle to window
                int id, // hot key identifier
                KeyModifiers fsModifiers, // key-modifier options
                Keys vk // virtual-key code
                );

                [DllImport("user32.dll", SetLastError=true)]
                public static extern bool UnregisterHotKey(
                IntPtr hWnd, // handle to window
                int id // hot key identifier
                );

                [Flags()]
                public enum KeyModifiers
                {
                Alt = 1,
                Control = 2,
                Shift = 4,
                Windows = 8
                }

                Now a sample use of the code: In Form load:

                bool success = RegisterHotKey(Handle, 100,
                KeyModifiers.Control | KeyModifiers.Shift, Keys.J);
                System.Diagnostics.Trace.WriteLine(
                "Success = " + success.ToString());

                In Form closed or closing:

                UnregisterHotKey(Handle, 100);

                And finally override the WndProc so the message can be handled.

                protected override void WndProc( ref Message m )
                {
                const int WM_HOTKEY = 0x0312;

                switch(m.Msg)
                {
                case WM\_HOTKEY:
                	MessageBox.Show("Hotkey pressed");
                	break;
                }
                
                base.WndProc(ref m );
                

                }

                HTH, James "And we are all men; apart from the females." - Colin Davies

                L Offline
                L Offline
                leppie
                wrote on last edited by
                #7

                Interesting :) Just a question James... In the Interop Marshalling section (Platform Invoke Data Types) in MSDN it states: BOOL as Unmanaged type in Wtypes.h = long in Unmanaged C++ = System.Int32 as Managed type. Looking at your code, is it possible to allways use bool instead of int as long as the returned value does not hold somethin like an error code? Also, in alot of examples I see them using int for a DWORD which really translates to uint. OK, I understand it will work, but only if int => 0. Why not use uint in the first place? This is all getting a bit overcomplicated to me. I think probably the best is to keep it simple. Try the logical way, if fail, do the way according to Platform Invoke Data Types Table. Suggestions? Cheers :) MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                J 1 Reply Last reply
                0
                • L leppie

                  Interesting :) Just a question James... In the Interop Marshalling section (Platform Invoke Data Types) in MSDN it states: BOOL as Unmanaged type in Wtypes.h = long in Unmanaged C++ = System.Int32 as Managed type. Looking at your code, is it possible to allways use bool instead of int as long as the returned value does not hold somethin like an error code? Also, in alot of examples I see them using int for a DWORD which really translates to uint. OK, I understand it will work, but only if int => 0. Why not use uint in the first place? This is all getting a bit overcomplicated to me. I think probably the best is to keep it simple. Try the logical way, if fail, do the way according to Platform Invoke Data Types Table. Suggestions? Cheers :) MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                  J Offline
                  J Offline
                  James T Johnson
                  wrote on last edited by
                  #8

                  As you've found out, all that is important is that the size be the same. However some things will get marshaled back and forth correctly. The conversion between BOOL and LONG to bool will marshal correctly so that the bool will have a true/false value. Using unsigned types in .NET isn't really discouraged but doing so makes the code non-CLS compliant so that code may not be portable to other languages or even used by them should they not support the same unsigned types. Thats my understanding anyway ;) James "And we are all men; apart from the females." - Colin Davies

                  L 1 Reply Last reply
                  0
                  • J James T Johnson

                    As you've found out, all that is important is that the size be the same. However some things will get marshaled back and forth correctly. The conversion between BOOL and LONG to bool will marshal correctly so that the bool will have a true/false value. Using unsigned types in .NET isn't really discouraged but doing so makes the code non-CLS compliant so that code may not be portable to other languages or even used by them should they not support the same unsigned types. Thats my understanding anyway ;) James "And we are all men; apart from the females." - Colin Davies

                    L Offline
                    L Offline
                    leppie
                    wrote on last edited by
                    #9

                    Ahh, thx James. Didnt know about unsigned types being non CLS compliant. re BOOL, i just made a small function to take care of it , but with this input i'll try converting some of them as see the results. The only remaining worry is what happens when DWORD return a value bigger than Int32.MaxValue? Not that it has happened yet, but it could. MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                    J 1 Reply Last reply
                    0
                    • L leppie

                      Ahh, thx James. Didnt know about unsigned types being non CLS compliant. re BOOL, i just made a small function to take care of it , but with this input i'll try converting some of them as see the results. The only remaining worry is what happens when DWORD return a value bigger than Int32.MaxValue? Not that it has happened yet, but it could. MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                      J Offline
                      J Offline
                      James T Johnson
                      wrote on last edited by
                      #10

                      leppie wrote: The only remaining worry is what happens when DWORD return a value bigger than Int32.MaxValue? Not that it has happened yet, but it could. Unfortunately thats just something you have to know ahead of time and it depends on how the value is used. If the DWORD contains something larger than Int32.MaxValue the return result will be negative as the LSB or MSB will be set (I never can remember how it should be ordered :(() James "And we are all men; apart from the females." - Colin Davies

                      L 1 Reply Last reply
                      0
                      • J James T Johnson

                        leppie wrote: The only remaining worry is what happens when DWORD return a value bigger than Int32.MaxValue? Not that it has happened yet, but it could. Unfortunately thats just something you have to know ahead of time and it depends on how the value is used. If the DWORD contains something larger than Int32.MaxValue the return result will be negative as the LSB or MSB will be set (I never can remember how it should be ordered :(() James "And we are all men; apart from the females." - Colin Davies

                        L Offline
                        L Offline
                        leppie
                        wrote on last edited by
                        #11

                        Thx again James :) James T. Johnson wrote: If the DWORD contains something larger than Int32.MaxValue the return result will be negative as the LSB or MSB will be set (I never can remember how it should be ordered ) According to MSDN an overflow exception will occur unless the block is marked unchecked. In which case the MSB/LSB (hell i dont know either, will wait till next year when I'm doing bitwise operations more regularly) will be set. MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                        J 1 Reply Last reply
                        0
                        • L leppie

                          Thx again James :) James T. Johnson wrote: If the DWORD contains something larger than Int32.MaxValue the return result will be negative as the LSB or MSB will be set (I never can remember how it should be ordered ) According to MSDN an overflow exception will occur unless the block is marked unchecked. In which case the MSB/LSB (hell i dont know either, will wait till next year when I'm doing bitwise operations more regularly) will be set. MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                          J Offline
                          J Offline
                          James T Johnson
                          wrote on last edited by
                          #12

                          leppie wrote: According to MSDN an overflow exception will occur unless the block is marked unchecked. I don't see this case happening, because when the data is being marshalled the framework doesn't know the original context of the value (signed or unsigned it is still a 4-byte block of memory). In this case we are telling it to be interpreted as a signed integer so it should interpret any value with the MSB or LSB set as being negative (assuming 2's complement use of the bits). The only cases where the MSB/LSB is set are when you have values larger than Int32.MaxValue. There may be some attributes that could be applied to make the framework aware of such occurances, but I'm not aware of them off the top of my head. Now when you add 2 ints together in managed code the framework does know the context of those values so it can decide whether or not the result went over the max value. James "And we are all men; apart from the females." - Colin Davies

                          L 1 Reply Last reply
                          0
                          • J James T Johnson

                            leppie wrote: According to MSDN an overflow exception will occur unless the block is marked unchecked. I don't see this case happening, because when the data is being marshalled the framework doesn't know the original context of the value (signed or unsigned it is still a 4-byte block of memory). In this case we are telling it to be interpreted as a signed integer so it should interpret any value with the MSB or LSB set as being negative (assuming 2's complement use of the bits). The only cases where the MSB/LSB is set are when you have values larger than Int32.MaxValue. There may be some attributes that could be applied to make the framework aware of such occurances, but I'm not aware of them off the top of my head. Now when you add 2 ints together in managed code the framework does know the context of those values so it can decide whether or not the result went over the max value. James "And we are all men; apart from the females." - Colin Davies

                            L Offline
                            L Offline
                            leppie
                            wrote on last edited by
                            #13

                            Thx James, you dont seem to overlook anything. How do u do it? Of course the the unmanaged function has no clue to what it is returning its returned value to. :) And I continue to slap myself repeatedly..... MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                            J 1 Reply Last reply
                            0
                            • L leppie

                              Thx James, you dont seem to overlook anything. How do u do it? Of course the the unmanaged function has no clue to what it is returning its returned value to. :) And I continue to slap myself repeatedly..... MYrc : A .NET IRC client with C# Plugin Capabilities. See http://sourceforge.net/projects/myrc for more info. :-D

                              J Offline
                              J Offline
                              James T Johnson
                              wrote on last edited by
                              #14

                              leppie wrote: Thx James, you dont seem to overlook anything. How do u do it? I have no real social life and I've worked with .NET since Beta 1; chances are that I've already had to think a lot of issues through at one time or another ;) Other times something just comes to me that seems to fit and makes sense when I think it through; such was the case here when returning values from unmanaged functions. In this case it was my 10 week long assembly course I took my first year of uni where we spent about 2 weeks on how the processor stores numbers (bitwise). James "And we are all men; apart from the females." - Colin Davies

                              1 Reply Last reply
                              0
                              Reply
                              • Reply as topic
                              Log in to reply
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes


                              • Login

                              • Don't have an account? Register

                              • Login or register to search.
                              • First post
                                Last post
                              0
                              • Categories
                              • Recent
                              • Tags
                              • Popular
                              • World
                              • Users
                              • Groups