我想做的功能是:程序在后台待命,然后用户点击或双击鼠标,程序就会播放设置过的声音,这样,现在卡在了后台获取鼠标按键信息。
(程序内的,重写winform的某个方法,就能很简单就得到,但是切到外面就无效了)网上搜到的结果都是用api的全局鼠标钩子,我尝试过用GetMessage获取windows消息然后分出鼠标的,[DllImport("user32", EntryPoint = "GetMessage")]
            public static extern uint GetMessage(
                            out tagMSG lpMsg,
                            IntPtr  hwnd,
                            int wMsgFilterMin,
                            int wMsgFilterMax
            );[StructLayout(LayoutKind.Sequential)] 
        public struct tagMSG
        {
            public int hwnd;
            public uint message;
            public int wParam;
            public long lParam;
            public uint time;
            public POINTAPI pt;
        }
                [StructLayout(LayoutKind.Sequential)]
        public struct POINTAPI
        {
            public int x;
            public int y;
        }在winform内调用线程,循环while (true )
                {
                    
                    if (GetMessage(ref  Msgs, new IntPtr(), 0, 0))
                        {
                         msglist.Add(Msgs.message.ToString());//先把所以消息取出,存到msglist的List里然后筛选
                    }
                   
                    }
但是GetMessage卡住了,根本不循环,整个线程锁在了if (GetMessage(ref  Msgs, new IntPtr(), 0, 0))这行。又搜到了关于
MouseProc的格式,LRESULT CALLBACK MouseProc(          int nCode,
    WPARAM wParam,
    LPARAM lParam
);
可是不会用,于是求教如何在后台获得鼠标的按键,
最好有完整的可运行的代码的例子,能运行的代码例子
,我网上搜了很多例子,有的是不完整,自己改了也运行不了,于是不会用,有的则是完整了也运行不了,出现意外错误,
我的是32位win7系统,不知道会不会系统有影响,另外api什么的好费解啊,到底是怎么调用许多查api 的查到的就一个方法名和方法的作用,参数和返回类型都没,不知道如何用,有的则是参数返回类型都有也有说明,但是有些类型是自定义的,搞不清楚到底是啥类型,这头疼啊非要找到完整套用的例子,才知道下次该如何使用,囧没分了,分全给出来了~求教啊~

解决方案 »

  1.   

    while (true )
                    {
                        
                        if (GetMessage(ref  Msgs, new IntPtr(), 0, 0))
                            {
                             msglist.Add(Msgs.message.ToString());//tbao http://www.58gw.net 先把所以消息取出,存到msglist的List里然后筛选
                        }
                       
                        }
      

  2.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using System.Reflection;namespace pixpicture
    {    //Declare wrapper managed POINT class. 
        [StructLayout(LayoutKind.Sequential)]
        public class POINT
        {
            public int x;
            public int y;
        }    //Declare wrapper managed MouseHookStruct class. 
        [StructLayout(LayoutKind.Sequential)]
        public class MouseHookStruct
        {
            public POINT pt;
            public int hwnd;
            public int wHitTestCode;
            public int dwExtraInfo;
        }    //Declare wrapper managed KeyboardHookStruct class. 
        [StructLayout(LayoutKind.Sequential)]
        public class KeyboardHookStruct
        {
            public int vkCode; //Specifies a virtual-key code. The code must be a value in the range 1 to 254. 
            public int scanCode; // Specifies a hardware scan code for the key. 
            public int flags; // Specifies the extended-key flag, event-injected flag, context code, and transition-state flag. 
            public int time; // Specifies the time stamp for this message. 
            public int dwExtraInfo; // Specifies extra information associated with the message. 
        }    public class GlobalHook
        {
            public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);        public GlobalHook()
            {
                Start();
            }        ~GlobalHook()
            {
                Stop();
            }        public event MouseEventHandler OnMouseActivity;
            public event KeyEventHandler KeyDown;
            public event KeyPressEventHandler KeyPress;
            public event KeyEventHandler KeyUp;        public delegate int GlobalHookProc(int nCode, Int32 wParam, IntPtr lParam);        static int hMouseHook = 0; //Declare mouse hook handle as int. 
            static int hKeyboardHook = 0; //Declare keyboard hook handle as int.         //values from Winuser.h in Microsoft SDK. 
            public const int WH_MOUSE_LL = 14; //mouse hook constant 
            public const int WH_KEYBOARD_LL = 13; //keyboard hook constant         GlobalHookProc MouseHookProcedure; //Declare MouseHookProcedure as HookProc type. 
            GlobalHookProc KeyboardHookProcedure; //Declare KeyboardHookProcedure as HookProc type.         //Import for SetWindowsHookEx function. 
            //Use this function to install a hook. 
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern int SetWindowsHookEx(int idHook, GlobalHookProc lpfn,
            IntPtr hInstance, int threadId);        //Import for UnhookWindowsHookEx. 
            //Call this function to uninstall the hook. 
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern bool UnhookWindowsHookEx(int idHook);        //Import for CallNextHookEx. 
            //Use this function to pass the hook information to next hook procedure in chain. 
            [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
            public static extern int CallNextHookEx(int idHook, int nCode,
            Int32 wParam, IntPtr lParam);        public void Start()
            {
                // install Mouse hook 
                if (hMouseHook == 0)
                {
                    // Create an instance of HookProc. 
                    MouseHookProcedure = new GlobalHookProc(MouseHookProc);                try
                    {
                        hMouseHook = SetWindowsHookEx(WH_MOUSE_LL,
                        MouseHookProcedure,
                        Marshal.GetHINSTANCE(
                        Assembly.GetExecutingAssembly().GetModules()[0]),
                        0);
                    }
                    catch (Exception err)
                    { }                //If SetWindowsHookEx fails. 
                    if (hMouseHook == 0)
                    {
                        Stop();
                        throw new Exception("SetWindowsHookEx failed.");
                    }
                }            // install Keyboard hook 
                if (hKeyboardHook == 0)
                {
                    KeyboardHookProcedure = new GlobalHookProc(KeyboardHookProc);
                    try
                    {
                        hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL,
                        KeyboardHookProcedure,
                        Marshal.GetHINSTANCE(
                        Assembly.GetExecutingAssembly().GetModules()[0]),
                        0);
                    }
                    catch (Exception err2)
                    { }                //If SetWindowsHookEx fails. 
                    if (hKeyboardHook == 0)
                    {
                        Stop();
                        throw new Exception("SetWindowsHookEx ist failed.");
                    }
                }
            }        public void Stop()
            {
                bool retMouse = true;
                bool retKeyboard = true;
                if (hMouseHook != 0)
                {
                    retMouse = UnhookWindowsHookEx(hMouseHook);
                    hMouseHook = 0;
                }            if (hKeyboardHook != 0)
                {
                    retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                    hKeyboardHook = 0;
                }            //If UnhookWindowsHookEx fails. 
                if (!(retMouse && retKeyboard))
                    throw new Exception("UnhookWindowsHookEx failed.");
            }        private const int WM_MOUSEMOVE = 0x200;
            private const int WM_LBUTTONDOWN = 0x201;
            private const int WM_RBUTTONDOWN = 0x204;
            private const int WM_MBUTTONDOWN = 0x207;
            private const int WM_LBUTTONUP = 0x202;
            private const int WM_RBUTTONUP = 0x205;
            private const int WM_MBUTTONUP = 0x208;
            private const int WM_LBUTTONDBLCLK = 0x203;
            private const int WM_RBUTTONDBLCLK = 0x206;
            private const int WM_MBUTTONDBLCLK = 0x209;        private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
            {
                // if ok and someone listens to our events 
                if ((nCode >= 0) && (OnMouseActivity != null))
                {
                    MouseButtons button = MouseButtons.None;
                    switch (wParam)
                    {
                        case WM_LBUTTONDOWN:
                            //case WM_LBUTTONUP: 
                            //case WM_LBUTTONDBLCLK: 
                            button = MouseButtons.Left;
                            break;
                        case WM_RBUTTONDOWN:
                            //case WM_RBUTTONUP: 
                            //case WM_RBUTTONDBLCLK: 
                            button = MouseButtons.Right;
                            break;
                    }
                    int clickCount = 0;
                    if (button != MouseButtons.None)
                        if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK)
                            clickCount = 2;
                        else
                            clickCount = 1;                //Marshall the data from callback. 
                    MouseHookStruct MyMouseHookStruct =
                    (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
                    MouseEventArgs e = new MouseEventArgs(
                    button,
                    clickCount,
                    MyMouseHookStruct.pt.x,
                    MyMouseHookStruct.pt.y,
                    0);
                    OnMouseActivity(this, e);
                }
                return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
            }这个是完整的,接下一楼
    结贴了~
      

  3.   

            //The ToAscii function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The function translates the code using the input language and physical keyboard layout identified by the keyboard layout handle. 
            [DllImport("user32")]
            public static extern int ToAscii(int uVirtKey, //[in] Specifies the virtual-key code to be translated. 
            int uScanCode, // [in] Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed). 
            byte[] lpbKeyState, // [in] Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down (pressed). The low bit, if set, indicates that the key is toggled on. In this function, only the toggle bit of the CAPS LOCK key is relevant. The toggle state of the NUM LOCK and SCROLL LOCK keys is ignored. 
            byte[] lpwTransKey, // [out] Pointer to the buffer that receives the translated character or characters. 
            int fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.         //The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer. 
            [DllImport("user32")]
            public static extern int GetKeyboardState(byte[] pbKeyState);        private const int WM_KEYDOWN = 0x100;
            private const int WM_KEYUP = 0x101;
            private const int WM_SYSKEYDOWN = 0x104;
            private const int WM_SYSKEYUP = 0x105;        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
            {
                // it was ok and someone listens to events 
                if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
                {
                    KeyboardHookStruct MyKeyboardHookStruct =
                    (KeyboardHookStruct)Marshal.PtrToStructure(lParam,
                    typeof(KeyboardHookStruct));
                    // raise KeyDown 
                    if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
                    {
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                        KeyEventArgs e = new KeyEventArgs(keyData);
                        KeyDown(this, e);
                    }                // raise KeyPress 
                    if (KeyPress != null && wParam == WM_KEYDOWN)
                    {
                        byte[] keyState = new byte[256];
                        GetKeyboardState(keyState);                    byte[] inBuffer = new byte[2];
                        if (ToAscii(MyKeyboardHookStruct.vkCode,
                        MyKeyboardHookStruct.scanCode,
                        keyState,
                        inBuffer,
                        MyKeyboardHookStruct.flags) == 1)
                        {
                            KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
                            KeyPress(this, e);
                        }
                    }                // raise KeyUp 
                    if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
                    {
                        Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                        KeyEventArgs e = new KeyEventArgs(keyData);
                        KeyUp(this, e);
                    }
                }
                return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
            }
        }
    }
    /*然后,给出调用示例using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Text; 
    using System.Windows.Forms; 
    using System.IO; namespace Test 

    public partial class FormMain : Form 

    private GlobalHook hook; ////////////////////////////////////////////////////////////////////// 
    //全局钩子 
    //鼠标处理程序 
    private void MyMouseClick(object sender, System.Windows.Forms.MouseEventArgs e) 

    if (e.Button == System.Windows.Forms.MouseButtons.Left) 
    this.label1.Text = "坐标:X= " + e.X + " Y=" + e.Y; 
    } //键盘处理程序 
    private void MyKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) 

    this.label1.Text = e.KeyCode.ToString(); 

    private void FormMain_Load(object sender, EventArgs e) 

    //全局钩子 
    hook = new GlobalHook(); 
    hook.KeyDown += new KeyEventHandler(this.MyKeyDown); 
    hook.OnMouseActivity += new MouseEventHandler(this.MyMouseClick); 
    hook.Start(); } private void FormMain_FormClosing(object sender, FormClosingEventArgs e) 

    //全局钩子 
    if (hook != null) hook.Stop(); 
    } } 
    }
     */完整的,接上一楼