1. 程式人生 > >C#中呼叫Windows訊息處理

C#中呼叫Windows訊息處理

引入User32.dll中的方法進行處理:

    public class Win32ApiMessage
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct MSG
        {
            public IntPtr Hwnd;
            public uint Message;
            public IntPtr WParam;
            public IntPtr LParam;
            public uint Time;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                this.X = x;
                this.Y = y;
            }
            public override string ToString()
            {
                return ("X:" + X + ", Y:" + Y);
            }
        }


        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);
        [DllImport("User32.dll", EntryPoint = "GetMessage")]
        public static extern bool GetMessage(ref MSG msg, int hWnd, uint wFilterMin, uint wFilterMax);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PeekMessage(
           ref MSG lpMsg,
           int hwnd,
           int wMsgFilterMin,
           int wMsgFilterMax,
           PeekMessageOption wRemoveMsg);

        public enum PeekMessageOption
        {
            PM_NOREMOVE = 0,
            PM_REMOVE
        }

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool TranslateMessage(ref MSG lpMsg);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern Int32 DispatchMessage(ref MSG lpMsg);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool GetCursorPos(out POINT pt);
    }