示例#1
0
        /// <summary>
        /// Functionally the same as WaitOne(), but pumps com messa
        /// </summary>
        /// <param name="handle"></param>
        public static void HackyComWaitOne(WaitHandle handle)
        {
            uint nativeResult; // result of the native wait API (WaitForMultipleObjects or MsgWaitForMultipleObjectsEx)
            int managedResult; // result to return from WaitHelper

            IntPtr[] waitHandles = new IntPtr[]{
                handle.SafeWaitHandle.DangerousGetHandle() };
            uint count = 1;

            uint QS_MASK = NativeMethods.QS_ALLINPUT; // message queue status
            QS_MASK = 0; //bizhawk edit?? did we need any messages here?? apparently not???

            // the core loop
            var msg = new NativeMethods.MSG();
            while (true)
            {
                // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns,
                // even if there's a message already seen but not removed in the message queue
                nativeResult = NativeMethods.MsgWaitForMultipleObjectsEx(
                        count, waitHandles,
                        (uint)0xFFFFFFFF,
                        QS_MASK,
                        NativeMethods.MWMO_INPUTAVAILABLE);

                if (IsNativeWaitSuccessful(count, nativeResult, out managedResult) || WaitHandle.WaitTimeout == managedResult)
                    break;
                // there is a message, pump and dispatch it
                if (NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
                {
                    NativeMethods.TranslateMessage(ref msg);
                    NativeMethods.DispatchMessage(ref msg);
                }
            }
            //m64pFrameComplete.WaitOne();
        }
        /// <include file='doc\StyleBuilderForm.uex' path='docs/doc[@for="StyleBuilderForm.WndProc"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == NativeMethods.WM_TIMER)
            {
                if (m.WParam == (IntPtr)DELAY_LOAD_TIMERID)
                {
                    IntPtr formHandle = Handle;
                    NativeMethods.KillTimer(formHandle, (IntPtr)DELAY_LOAD_TIMERID);

                    NativeMethods.MSG msg = new NativeMethods.MSG();
                    if (!NativeMethods.PeekMessage(ref msg, formHandle, 0, 0, NativeMethods.PM_NOREMOVE))
                    {
                        DoDelayLoadActions();
                    }
                    else
                    {
                        StartDelayLoadTimer();
                    }
                    return;
                }
            }
            else if (m.Msg == NativeMethods.WM_SYSCOLORCHANGE)
            {
                pageSelector.BackColor = SystemColors.Control;
            }
            base.WndProc(ref m);
        }
        private void WndThread()
        {
            IntPtr hInstance = Marshal.GetHINSTANCE(Application.Current.GetType().Module);
            var    wndClass  = new NativeMethods.WNDCLASSEX
            {
                cbSize        = (uint)Marshal.SizeOf(typeof(NativeMethods.WNDCLASSEX)),
                lpszClassName = _className,
                lpfnWndProc   = WndProc,
                hInstance     = hInstance,
            };

            NativeMethods.RegisterClassEx(ref wndClass);

            IntPtr _hWnd = NativeMethods.CreateWindowEx(0, _className, _windowName, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, hInstance, IntPtr.Zero);

            if (_hWnd == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            NativeMethods.MSG msg = default;
            while (NativeMethods.GetMessage(out msg, _hWnd, 0, 0) != 0)
            {
                NativeMethods.TranslateMessage(ref msg);
                NativeMethods.DispatchMessage(ref msg);
            }
        }
示例#4
0
 public int TranslateAccelerator(
     ref NativeMethods.MSG msg,
     ref Guid group,
     int nCmdID)
 {
     // No translation here.
     return(NativeMethods.SRESULTS.S_FALSE);
 }
示例#5
0
        public void ThreadContext_EmptyProcessFiltersWorks()
        {
            // Test that no filters at all does not throw, and that returns false from translation
            Application.ThreadContext threadContext = new Application.ThreadContext();
            NativeMethods.MSG         msg           = new NativeMethods.MSG();
            bool result = threadContext.PreTranslateMessage(ref msg);

            Assert.False(result);
        }
        int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref NativeMethods.MSG msg, ref Guid group, int nCmdID)
        {
            Message message = Message.Create(msg.hwnd, msg.message, msg.wParam, msg.lParam);
            bool    handled = this.Parent.TranslateAccelerator(ref message);

            msg.hwnd    = message.HWnd;
            msg.message = message.Msg;
            msg.wParam  = message.WParam;
            msg.lParam  = message.LParam;
            return((handled) ? UnsafeNativeMethods.HRESULT.S_OK : UnsafeNativeMethods.HRESULT.S_FALSE);
        }
示例#7
0
        // ------------------------------------------------------
        //
        // Private Methods
        //
        // ------------------------------------------------------

        #region Private Methods

        // Infinite loop. Wait for queue items to be processed.
        private void WaitForWork()
        {
            SafeWaitHandle handle = _ev.SafeWaitHandle;

            NativeMethods.MSG msg = new NativeMethods.MSG();

            while (true)
            {
                try
                {
                    // pump any messages
                    while (UnsafeNativeMethods.PeekMessage(ref msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
                    {
                        if (msg.message == NativeMethods.WM_QUIT)
                        {
                            break;
                        }
                        Misc.DispatchMessage(ref msg);
                    }

                    // do any work items in the queue
                    // It's possible items could be enqueued between when we check for the count
                    // and dequeue but the event is set then and we'll come back into DrainQueue.
                    // (note: don't use a for loop here because as the counter is incremented
                    // Count is decremented and we'll only process half the queue)
                    while (_q.Count > 0)
                    {
                        // pull an item off the queue, process, then clear it
                        QueueItem item = (QueueItem)_q.Dequeue();

                        item.Process();
                    }

                    int result = Misc.MsgWaitForMultipleObjects(handle, false, NativeMethods.INFINITE, NativeMethods.QS_ALLINPUT);
                    if (result == NativeMethods.WAIT_FAILED || result == NativeMethods.WAIT_TIMEOUT)
                    {
                        Debug.Assert(false, "MsgWaitForMultipleObjects failed while WaitForWork");
                        break;
                    }
                }
                catch (Exception e)
                {
                    if (Misc.IsCriticalException(e))
                    {
                        throw;
                    }

                    // Might happen when if the hwnd goes away between the peek and the dispatch
                }
                //
            }
        }
        public void ThreadContext_MultipleProcessFiltersProcesses()
        {
            // Test that multiple filters work
            Application.ThreadContext threadContext = new Application.ThreadContext();

            int filterId2    = TestMessageId2;
            var mockContext2 = new Mock <IMessageFilter>(MockBehavior.Strict);

            mockContext2.Setup(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny))
            .Returns((MessageCallback)((ref Message m) => m.Msg == filterId2));
            threadContext.AddMessageFilter(mockContext2.Object);

            int filterId3    = TestMessageId3;
            var mockContext3 = new Mock <IMessageFilter>(MockBehavior.Strict);

            mockContext3.Setup(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny))
            .Returns((MessageCallback)((ref Message m) => m.Msg == filterId3));
            threadContext.AddMessageFilter(mockContext3.Object);


            NativeMethods.MSG msg = new NativeMethods.MSG
            {
                message = TestMessageId1
            };
            bool result = threadContext.PreTranslateMessage(ref msg);

            Assert.False(result);

            mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(1));
            mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(1));


            msg = new NativeMethods.MSG
            {
                message = TestMessageId2
            };
            result = threadContext.PreTranslateMessage(ref msg);
            Assert.True(result);

            mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(2));
            mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(1));

            msg = new NativeMethods.MSG
            {
                message = TestMessageId3
            };
            result = threadContext.PreTranslateMessage(ref msg);
            Assert.True(result);

            mockContext2.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(3));
            mockContext3.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(2));
        }
示例#9
0
 private IntPtr MessageHook(int nCode, IntPtr wParam, IntPtr lParam)
 {
     if (nCode == NativeMethods.MSGF_MENU)//截获Menu消息
     {
         NativeMethods.MSG msg = (NativeMethods.MSG)Marshal.PtrToStructure(lParam, typeof(NativeMethods.MSG));
         Message           m   = Message.Create(msg.hwnd, msg.message, msg.wParam, msg.lParam);
         if (MessageFilter(ref m))
         {
             return((IntPtr)1);
         }
     }
     return(UnsafeNativeMethods.CallNextHookEx(new HandleRef(this, messageHookHandle), nCode, wParam, lParam));
 }
示例#10
0
        public void ThreadContext_WrongProcessFiltersPassesThrough()
        {
            // Test that a filter for the wrong ID returns false, but does get called
            Application.ThreadContext threadContext = new Application.ThreadContext();

            int filterId    = TestMessageId2;
            var mockContext = new Mock <IMessageFilter>(MockBehavior.Strict);

            mockContext.Setup(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny))
            .Returns((MessageCallback)((ref Message m) => m.Msg == filterId));

            threadContext.AddMessageFilter(mockContext.Object);
            NativeMethods.MSG msg = new NativeMethods.MSG();
            msg.message = TestMessageId1;
            bool result = threadContext.PreTranslateMessage(ref msg);

            Assert.False(result);
            mockContext.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(1));
        }
示例#11
0
        public void ThreadContext_CorrectProcessFiltersProcesses()
        {
            // Test that a filter with the correct ID returns true
            Application.ThreadContext threadContext = new Application.ThreadContext();

            int filterId    = TestMessageId2;
            var mockContext = new Mock <IMessageFilter>(MockBehavior.Strict);

            mockContext.Setup(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny))
            .Returns((MessageCallback)((ref Message m) => m.Msg == filterId));

            threadContext.AddMessageFilter(mockContext.Object);
            NativeMethods.MSG msg = new NativeMethods.MSG();
            msg.message = filterId;
            bool result = threadContext.PreTranslateMessage(ref msg);

            Assert.True(result);
            mockContext.Verify(c => c.PreFilterMessage(ref It.Ref <Message> .IsAny), Times.Exactly(1));
        }
示例#12
0
        /// <summary>
        /// Functionally the same as WaitOne(), but pumps com messa
        /// </summary>
        /// <param name="handle"></param>
        public static void HackyComWaitOne(WaitHandle handle)
        {
            uint nativeResult;             // result of the native wait API (WaitForMultipleObjects or MsgWaitForMultipleObjectsEx)
            int  managedResult;            // result to return from WaitHelper

            IntPtr[] waitHandles = new IntPtr[] {
                handle.SafeWaitHandle.DangerousGetHandle()
            };
            uint count = 1;

            uint QS_MASK = NativeMethods.QS_ALLINPUT; // message queue status

            QS_MASK = 0;                              //bizhawk edit?? did we need any messages here?? apparently not???

            // the core loop
            var msg = new NativeMethods.MSG();

            while (true)
            {
                // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns,
                // even if there's a message already seen but not removed in the message queue
                nativeResult = NativeMethods.MsgWaitForMultipleObjectsEx(
                    count, waitHandles,
                    (uint)0xFFFFFFFF,
                    QS_MASK,
                    NativeMethods.MWMO_INPUTAVAILABLE);

                if (IsNativeWaitSuccessful(count, nativeResult, out managedResult) || WaitHandle.WaitTimeout == managedResult)
                {
                    break;
                }
                // there is a message, pump and dispatch it
                if (NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
                {
                    NativeMethods.TranslateMessage(ref msg);
                    NativeMethods.DispatchMessage(ref msg);
                }
            }
            //m64pFrameComplete.WaitOne();
        }
示例#13
0
 public virtual int TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID)
 {
     return(NativeMethods.S_FALSE);
 }
示例#14
0
 public virtual int TranslateAccelerator(ref NativeMethods.MSG msg, ref Guid group, int nCmdID)
 {
     return(NativeMethods.S_OK);
 }
 /// <summary>
 ///     Creates a new document window pane which can be handed to the VS
 ///     shell.
 /// </summary>
 /// <param name='window'>
 ///     The document window for the designer.
 /// </param>
 /// <param name='host'>
 ///     The designer host, through which we can obtain services.
 /// </param>
 public DocumentWindowPane(DocumentWindow window, IDesignerHost host)
 {
     this.window = window;
     this.host   = host;
     this.msg    = new NativeMethods.MSG();
 }
示例#16
0
        internal void ShowInvalidMessage(string propName, object value, Exception ex) {

            if (value == null) {
                value = "(null)";
            }

            if (propName == null) {
                propName = "(unknown)";
            }

            Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose,  "PropertyGridView:ShowInvalidMessage(prop=" + propName + ")");

            // we have to uninstall our hook so the user can push the button!
            bool hooked = Edit.HookMouseDown;
            Edit.DisableMouseHook = true;
            SetCommitError(ERROR_MSGBOX_UP, false);

            // Fix for NdpWhidbey#28082: Before invoking the error dialog, flush all mouse messages in the message queue.
            // Otherwise the click that triggered the error will still be in the queue, and will get eaten by the dialog,
            // potentially causing an accidental button click. Problem occurs because we trap clicks using a system hook,
            // which usually discards the message by returning 1 to GetMessage(). But this won't occur until after the
            // error dialog gets closed, which is much too late.
            NativeMethods.MSG mouseMsg = new NativeMethods.MSG();
            while (UnsafeNativeMethods.PeekMessage(ref mouseMsg,
                                                   NativeMethods.NullHandleRef,
                                                   NativeMethods.WM_MOUSEFIRST,
                                                   NativeMethods.WM_MOUSELAST,
                                                   NativeMethods.PM_REMOVE))
                ;

            // These things are just plain useless.
            //
            if (ex is System.Reflection.TargetInvocationException) {
                ex = ex.InnerException;
            }

            // Try to find an exception message to display
            //
            string exMessage = ex.Message;

            bool revert = false;

            while (exMessage == null || exMessage.Length == 0) {
                ex = ex.InnerException;
                if (ex == null) {
                    break;
                }
                exMessage = ex.Message;
            }
            
            IUIService uiSvc = (IUIService)GetService(typeof(IUIService));

            ErrorDialog.Message = SR.GetString(SR.PBRSErrorInvalidPropertyValue);
            ErrorDialog.Text = SR.GetString(SR.PBRSErrorTitle);
            ErrorDialog.Details = exMessage;
            

            if (uiSvc != null) {
                revert = (DialogResult.Cancel == uiSvc.ShowDialog(ErrorDialog));
            }
            else {
                revert = (DialogResult.Cancel == this.ShowDialog(ErrorDialog));
            }
            
            Edit.DisableMouseHook = false;

            if (hooked) {
                SelectGridEntry(selectedGridEntry, true);
            }
            SetCommitError(ERROR_THROWN, hooked);

            if (revert) {
                OnEscape(Edit);
            }
        }
示例#17
0
 public virtual int TranslateAccelerator(ref NativeMethods.MSG lpmsg, short wID)
 {
     Debug.WriteLineIf(StyleBuilder.StyleBuilderSwitch.TraceVerbose, "CTridentSite: IOleInPlaceFrame::TranslateAccelerator");
     return(NativeMethods.S_FALSE);
 }
示例#18
0
 public static extern bool TranslateMessage([In, Out] ref NativeMethods.MSG msg);
示例#19
0
文件: AxHost.cs 项目: JianwenSun/cc
 protected internal override bool ProcessMnemonic(char charCode) {
     Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "In AxHost.ProcessMnemonic: " + (int)charCode);
     if (CanSelect) {
         try {
             NativeMethods.tagCONTROLINFO ctlInfo = new NativeMethods.tagCONTROLINFO();
             int hr = GetOleControl().GetControlInfo(ctlInfo);
             if (NativeMethods.Failed(hr)) {
                 return false;
             }
             NativeMethods.MSG msg = new NativeMethods.MSG();
             // Sadly, we don't have a message so we must fake one ourselves...
             // A bit of ugliness here (a bit?  more like a bucket...)
             // The message we are faking is a WM_SYSKEYDOWN w/ the right alt key setting...
             msg.hwnd = (ContainingControl == null) ? IntPtr.Zero : ContainingControl.Handle;
             msg.message = NativeMethods.WM_SYSKEYDOWN;
             msg.wParam = (IntPtr) Char.ToUpper(charCode, CultureInfo.CurrentCulture);
             msg.lParam = (IntPtr) 0x20180001;
             msg.time = SafeNativeMethods.GetTickCount();
             NativeMethods.POINT p = new NativeMethods.POINT();
             UnsafeNativeMethods.GetCursorPos(p);
             msg.pt_x = p.x;
             msg.pt_y = p.y;
             if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) {
                 GetOleControl().OnMnemonic(ref msg);
                 Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Processed mnemonic " + msg);
                 Focus();
                 return true;
             }
         }
         catch (Exception t) {
             Debug.Fail("error in processMnemonic");
             Debug.Fail(t.ToString());
             return false;
         }
     }
     return false;
 }
 public void Relay(IntPtr wParam, IntPtr lParam)
 {
     var msg = new NativeMethods.MSG();
     msg.lParam = lParam;
     msg.wParam = wParam;
     msg.message = NativeMethods.WM_MOUSEMOVE;
     msg.hwnd = myParent.Handle;
     NativeMethods.SendMessage(Handle, NativeMethods.TTM_RELAYEVENT, 0, ref msg);
 }
示例#21
0
 internal static extern bool PeekMessage([In, Out] ref NativeMethods.MSG msg, IntPtr hwnd, int uMsgFilterMin, int uMsgFilterMax, int wRemoveMsg);
示例#22
0
 public static extern bool PeekMessage([In, Out] ref NativeMethods.MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove);
示例#23
0
 internal static extern int GetMessage([In, Out] ref NativeMethods.MSG msg, IntPtr hWnd, int uMsgFilterMin, int uMsgFilterMax);
示例#24
0
 internal static extern IntPtr DispatchMessage([In] ref NativeMethods.MSG msg);
示例#25
0
        static bool DoAssert(string message)
        {
            if (!s_assert)
            {
                return(false);
            }

            // Skip 2 frames - one for this function, one for
            // the public Assert function that called this function.
            System.Diagnostics.StackFrame frame = new System.Diagnostics.StackFrame(2, true);
            System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(2, true);

            string fileName   = frame.GetFileName();
            int    lineNumber = frame.GetFileLineNumber();

            string traceFormat;

            if (!string.IsNullOrEmpty(fileName))
            {
                traceFormat = "ASSERTION FAILED: {0}\nFile: {1}:{2}\nStack trace:\n{3}";
            }
            else
            {
                traceFormat = "ASSERTION FAILED: {0}\nStack trace:\n{3}";
            }

            string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, message, fileName, lineNumber, trace.ToString());

            if (!TraceBreak(TAG_ASSERT, traceMessage, null, true))
            {
                // If the value of "Assert" is not TagValue.Break, then don't even ask user.
                return(false);
            }

            if (s_assertBreak)
            {
                // If "AssertBreak" is enabled, then always break.
                return(true);
            }

            string dialogFormat;

            if (!string.IsNullOrEmpty(fileName))
            {
                dialogFormat =
                    @"Failed expression: {0}
File: {1}:{2}
Component: {3}
PID={4} TID={5}
Stack trace:
{6}

A=Exit process R=Debug I=Continue";
            }
            else
            {
                dialogFormat =
                    @"Failed expression: {0}
(no file information available)
Component: {3}
PID={4} TID={5}
Stack trace:
{6}

A=Exit process R=Debug I=Continue";
            }

            string dialogMessage = string.Format(
                CultureInfo.InvariantCulture,
                dialogFormat,
                message,
                fileName, lineNumber,
                COMPONENT,
                NativeMethods.GetCurrentProcessId(), NativeMethods.GetCurrentThreadId(),
                trace.ToString());

            MBResult mbResult = new MBResult();

            Thread thread = new Thread(
                delegate() {
                for (int i = 0; i < 100; i++)
                {
                    NativeMethods.MSG msg = new NativeMethods.MSG();
                    NativeMethods.PeekMessage(ref msg, new HandleRef(mbResult, IntPtr.Zero), 0, 0, NativeMethods.PM_REMOVE);
                }

                mbResult.Result = NativeMethods.MessageBox(new HandleRef(mbResult, IntPtr.Zero), dialogMessage, PRODUCT + " Assertion",
                                                           NativeMethods.MB_SERVICE_NOTIFICATION |
                                                           NativeMethods.MB_TOPMOST |
                                                           NativeMethods.MB_ABORTRETRYIGNORE |
                                                           NativeMethods.MB_ICONEXCLAMATION);
            }
                );

            thread.Start();
            thread.Join();

            if (mbResult.Result == NativeMethods.IDABORT)
            {
                IntPtr currentProcess = NativeMethods.GetCurrentProcess();
                NativeMethods.TerminateProcess(new HandleRef(mbResult, currentProcess), 1);
            }

            return(mbResult.Result == NativeMethods.IDRETRY);
        }
示例#26
0
        int NativeMethods.IDocHostUIHandler.TranslateAccelerator(ref NativeMethods.MSG msg, ref Guid group, int nCmdID)
        {
            Debug.WriteLineIf(StyleBuilder.StyleBuilderSwitch.TraceVerbose, "CTridentSite: IDocHostUIHandler::TranslateAccelerator");

            return(NativeMethods.S_OK);
        }
        public override bool PreProcessMessage(ref Message msg)
        {
            if (IsUserMode) {
                if (this.GetAXHostState(WebBrowserHelper.siteProcessedInputKey)) {
                    // In this case, the control called us back through IOleControlSite
                    // and is now giving us a chance to see if we want to process it.
                    return base.PreProcessMessage(ref msg);
                }


                // Convert Message to NativeMethods.MSG
                NativeMethods.MSG win32Message = new NativeMethods.MSG();
                win32Message.message = msg.Msg;
                win32Message.wParam = msg.WParam;
                win32Message.lParam = msg.LParam;
                win32Message.hwnd = msg.HWnd;

                this.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false);
                try 
                {
                    if (axOleInPlaceObject != null)
                    {
                        // Give the ActiveX control a chance to process this key by calling
                        // IOleInPlaceActiveObject::TranslateAccelerator.
                        int hr = axOleInPlaceActiveObject.TranslateAccelerator(ref win32Message);

                        if (hr == NativeMethods.S_OK)
                        {
                            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message translated to " + win32Message);
                            return true;
                        }
                        else
                        {
                            //
                            // win32Message may have been modified. Lets copy it back.
                            msg.Msg = win32Message.message;
                            msg.WParam = win32Message.wParam;
                            msg.LParam = win32Message.lParam;
                            msg.HWnd = win32Message.hwnd;

                            if (hr == NativeMethods.S_FALSE)
                            {
                                // Same code as in AxHost (ignore dialog keys here, as a fix for ASURT 139468).
                                // We have the same problem here (see DDB#147045).
                                bool ret = false;

                                ignoreDialogKeys = true;
                                try
                                {
                                    ret = base.PreProcessMessage(ref msg);
                                }
                                finally
                                {
                                    ignoreDialogKeys = false;
                                }
                                return ret;
                            }
                            else if (this.GetAXHostState(WebBrowserHelper.siteProcessedInputKey))
                            {
                                Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message processed by site. Calling base.PreProcessMessage() " + msg);
                                return base.PreProcessMessage(ref msg);
                            }
                            else
                            {
                                Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message not processed by site. Returning false. " + msg);
                                return false;
                            }
                        }
                    }
                }
                finally {
                    this.SetAXHostState(WebBrowserHelper.siteProcessedInputKey, false);
                }
            }
            
            return false;
        }
示例#28
0
文件: AxHost.cs 项目: JianwenSun/cc
        /// <include file='doc\AxHost.uex' path='docs/doc[@for="AxHost.PreProcessMessage"]/*' />
        /// <devdoc>
        ///     This method is called by the application's message loop to pre-process
        ///     input messages before they are dispatched. Possible values for the
        ///     msg.message field are WM_KEYDOWN, WM_SYSKEYDOWN, WM_CHAR, and WM_SYSCHAR.
        ///     If this method processes the message it must return true, in which case
        ///     the message loop will not dispatch the message.
        ///     This method should not be called directly by the user.
        ///
        ///     The keyboard processing of input keys to AxHost controls go in 3 steps inside AxHost.PreProcessMessage()
        ///
        ///    (1) Call the OCX's TranslateAccelarator. This may or may not call back into us using IOleControlSite::TranslateAccelarator()
        ///
        ///    (2) If the control completely processed this without calling us back: 
        ///         -- If this returns S_OK, then it means that the control already processed this message and we return true,
        ///            forcing us to not do any more processing or dispatch the message.
        ///         -- If this returns S_FALSE, then it means that the control wants us to dispatch the message without doing any processing on our side.
        ///
        ///    (3) If the control completely processed this by calling us back: 
        ///         -- If this returns S_OK, then it means that the control processed this message and we return true,
        ///            forcing us to not do any more processing or dispatch the message.
        ///         -- If this returns S_FALSE, then it means that the control did not process this message,
        ///            but we did, and so we should route it through our PreProcessMessage().
        /// </devdoc>
        public override bool PreProcessMessage(ref Message msg) {
            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "AxHost.PreProcessMessage " + msg.ToString());
            
            if (IsUserMode()) {
                if (axState[siteProcessedInputKey]) {
                    // In this case, the control called the us back through the IControlSite
                    // and giving us a chance to see if we want to process it. We in turn
                    // call the base implementation which normally would call the control's
                    // IsInputKey() or IsInputChar(). So, we short-circuit those to return false
                    // and only return true, if the container-chain wanted to process the keystroke
                    // (e.g. tab, accelarators etc.)
                    //
                    return base.PreProcessMessage(ref msg);
                }

                NativeMethods.MSG win32Message = new NativeMethods.MSG();
                win32Message.message = msg.Msg;
                win32Message.wParam = msg.WParam;
                win32Message.lParam = msg.LParam;
                win32Message.hwnd = msg.HWnd;
    
                axState[siteProcessedInputKey] = false;
                try {
                    UnsafeNativeMethods.IOleInPlaceActiveObject activeObj = GetInPlaceActiveObject();
                    if (activeObj != null)
                    {
                        int hr = activeObj.TranslateAccelerator(ref win32Message);

                        msg.Msg = win32Message.message;
                        msg.WParam = win32Message.wParam;
                        msg.LParam = win32Message.lParam;
                        msg.HWnd = win32Message.hwnd;

                        if (hr == NativeMethods.S_OK) {
                            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message translated by control to " + msg);
                            return true;
                        }
                        else if (hr == NativeMethods.S_FALSE) {
                            bool ret = false;

                            ignoreDialogKeys = true;
                            try {
                                ret = base.PreProcessMessage(ref msg);
                            }
                            finally {
                                ignoreDialogKeys = false;
                            }
                            return ret;
                        }
                        else if (axState[siteProcessedInputKey]) {
                            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message processed by site. Calling base.PreProcessMessage() " + msg);
                            return base.PreProcessMessage (ref msg);
                        }
                        else {
                            Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "\t Message not processed by site. Returning false. " + msg);
                            return false;
                        }
                    }
                }
                finally {
                    axState[siteProcessedInputKey] = false;
                }
            }
            
            return false;
        }
示例#29
0
        /// <summary>
        /// Wait for handles similar to SynchronizationContext.WaitHelper, but with pumping
        /// </summary>
        public static int WaitWithMessageLoop(IntPtr[] waitHandles, bool waitAll, int timeout)
        {
            // Don't use CoWaitForMultipleHandles, it has issues with message pumping
            // more info: http://stackoverflow.com/q/21226600/1768303

            const uint QS_MASK = NativeMethods.QS_ALLINPUT; // message queue status

            uint count = (uint)waitHandles.Length;

            if (waitHandles == null || count == 0)
            {
                throw new ArgumentNullException();
            }

            uint nativeResult;  // result of the native wait API (WaitForMultipleObjects or MsgWaitForMultipleObjectsEx)
            int  managedResult; // result to return from WaitHelper

            // wait for all?
            if (waitAll && count > 1)
            {
                // more: http://blogs.msdn.com/b/cbrumme/archive/2004/02/02/66219.aspx, search for "mutex"
                throw new NotSupportedException("WaitAll for multiple handles on a STA thread is not supported.");
            }
            else
            {
                // optimization: a quick check with a zero timeout
                nativeResult = NativeMethods.WaitForMultipleObjects(count, waitHandles, bWaitAll: false, dwMilliseconds: 0);
                if (IsNativeWaitSuccessful(count, nativeResult, out managedResult))
                {
                    return(managedResult);
                }

                // proceed to pumping

                // track timeout if not infinite
                Func <bool> hasTimedOut      = () => false;
                int         remainingTimeout = timeout;

                if (remainingTimeout != Timeout.Infinite)
                {
                    int startTick = Environment.TickCount;
                    hasTimedOut = () =>
                    {
                        // Environment.TickCount wraps correctly even if runs continuously
                        int lapse = Environment.TickCount - startTick;
                        remainingTimeout = Math.Max(timeout - lapse, 0);
                        return(remainingTimeout <= 0);
                    };
                }

                // the core loop
                var msg = new NativeMethods.MSG();
                while (true)
                {
                    // MsgWaitForMultipleObjectsEx with MWMO_INPUTAVAILABLE returns,
                    // even if there's a message already seen but not removed in the message queue
                    nativeResult = NativeMethods.MsgWaitForMultipleObjectsEx(
                        count, waitHandles,
                        (uint)remainingTimeout,
                        QS_MASK,
                        NativeMethods.MWMO_INPUTAVAILABLE);

                    if (IsNativeWaitSuccessful(count, nativeResult, out managedResult) || WaitHandle.WaitTimeout == managedResult)
                    {
                        return(managedResult);
                    }

                    // there is a message, pump and dispatch it
                    if (NativeMethods.PeekMessage(out msg, IntPtr.Zero, 0, 0, NativeMethods.PM_REMOVE))
                    {
                        NativeMethods.TranslateMessage(ref msg);
                        NativeMethods.DispatchMessage(ref msg);
                    }
                    if (hasTimedOut())
                    {
                        return(WaitHandle.WaitTimeout);
                    }
                }
            }
        }
示例#30
0
文件: Form.cs 项目: mind0n/hive
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
            if (base.ProcessCmdKey(ref msg, keyData)) return true;

            MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu);
            if (curMenu != null && curMenu.ProcessCmdKey(ref msg, keyData)) return true;

            // Process MDI accelerator keys.

            bool retValue = false;

            NativeMethods.MSG win32Message = new NativeMethods.MSG();
            win32Message.message = msg.Msg;
            win32Message.wParam = msg.WParam;
            win32Message.lParam = msg.LParam;
            win32Message.hwnd = msg.HWnd;

            if (ctlClient != null && ctlClient.Handle != IntPtr.Zero &&
                UnsafeNativeMethods.TranslateMDISysAccel(ctlClient.Handle, ref win32Message)) {

                retValue = true;
            }

            msg.Msg = win32Message.message;
            msg.WParam = win32Message.wParam;
            msg.LParam = win32Message.lParam;
            msg.HWnd = win32Message.hwnd;

            return retValue;
        }
示例#31
0
            /// <include file='doc\Application.uex' path='docs/doc[@for="Application.ComponentManager.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop"]/*' />
            /// <devdoc>
            ///      Component identified by dwComponentID (cookie returned from
            ///      FRegisterComponent) wishes to push a message loop for reason uReason.
            ///      uReason is one the values from the msoloop enumeration (above).
            ///      pvLoopData is data private to the component.
            ///      The component manager should push its message loop,
            ///      calling IMsoComponent::FContinueMessageLoop(uReason, pvLoopData)
            ///      during each loop iteration (see IMsoComponent::FContinueMessageLoop
            ///      comments).  When IMsoComponent::FContinueMessageLoop returns FALSE, the
            ///      component manager terminates the loop.
            ///      Returns TRUE if component manager terminates loop because component
            ///      told it to (by returning FALSE from IMsoComponent::FContinueMessageLoop),
            ///      FALSE if it had to terminate the loop for some other reason.  In the
            ///      latter case, component should perform any necessary action (such as
            ///      cleanup).
            /// </devdoc>
            bool UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(
                                                      IntPtr dwComponentID,
                                                      int reason,
                                                      int pvLoopData          // PVOID
                                                      ) {

                int dwLocalComponentID = unchecked((int)(long)dwComponentID);
                // Hold onto old state to allow restore before we exit...
                //
                int currentLoopState = currentState;
                bool continueLoop = true;

                if (!OleComponents.ContainsKey(dwLocalComponentID)) {
                    return false;
                }

                UnsafeNativeMethods.IMsoComponent prevActive = this.activeComponent;

                try {
                    // Execute the message loop until the active component tells us to stop.
                    //
                    NativeMethods.MSG msg = new NativeMethods.MSG();
                    NativeMethods.MSG[] rgmsg = new NativeMethods.MSG[] {msg};
                    bool unicodeWindow = false;
                    UnsafeNativeMethods.IMsoComponent requestingComponent;

                    ComponentHashtableEntry entry = (ComponentHashtableEntry)OleComponents[dwLocalComponentID];
                    if (entry == null) {
                        return false;
                    }



                    requestingComponent = entry.component;

                    this.activeComponent = requestingComponent;

                    Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Pushing message loop " + reason.ToString(CultureInfo.InvariantCulture));
                    Debug.Indent();

                    while (continueLoop) {

                        // Determine the component to route the message to
                        //
                        UnsafeNativeMethods.IMsoComponent component;

                        if (trackingComponent != null) {
                            component = trackingComponent;
                        }
                        else if (activeComponent != null) {
                            component = activeComponent;
                        }
                        else {
                            component = requestingComponent;
                        }

                        bool peeked = UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE);

                        if (peeked) {

                            rgmsg[0] = msg;
                            continueLoop = component.FContinueMessageLoop(reason, pvLoopData, rgmsg);

                            // If the component wants us to process the message, do it.
                            // The component manager hosts windows from many places.  We must be sensitive
                            // to ansi / Unicode windows here.
                            //
                            if (continueLoop) {
                                if (msg.hwnd != IntPtr.Zero && SafeNativeMethods.IsWindowUnicode(new HandleRef(null, msg.hwnd))) {
                                    unicodeWindow = true;
                                    UnsafeNativeMethods.GetMessageW(ref msg, NativeMethods.NullHandleRef, 0, 0);
                                }
                                else {
                                    unicodeWindow = false;
                                    UnsafeNativeMethods.GetMessageA(ref msg, NativeMethods.NullHandleRef, 0, 0);
                                }

                                if (msg.message == NativeMethods.WM_QUIT) {
                                    Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : Normal message loop termination");

                                    Application.ThreadContext.FromCurrent().DisposeThreadWindows();

                                    if (reason != NativeMethods.MSOCM.msoloopMain) {
                                        UnsafeNativeMethods.PostQuitMessage((int)msg.wParam);
                                    }

                                    continueLoop = false;
                                    break;
                                }

                                // Now translate and dispatch the message.
                                //
                                // Reading through the rather sparse documentation,
                                // it seems we should only call FPreTranslateMessage
                                // on the active component.  But frankly, I'm afraid of what that might break.
                                // See ASURT 29415 for more background.
                                if (!component.FPreTranslateMessage(ref msg)) {
                                    UnsafeNativeMethods.TranslateMessage(ref msg);
                                    if (unicodeWindow) {
                                        UnsafeNativeMethods.DispatchMessageW(ref msg);
                                    }
                                    else {
                                        UnsafeNativeMethods.DispatchMessageA(ref msg);
                                    }
                                }
                            }
                        }
                        else {

                            // If this is a DoEvents loop, then get out.  There's nothing left
                            // for us to do.
                            //
                            if (reason == NativeMethods.MSOCM.msoloopDoEvents ||
                                reason == NativeMethods.MSOCM.msoloopDoEventsModal) {
                                break;
                            }

                            // Nothing is on the message queue.  Perform idle processing
                            // and then do a WaitMessage.
                            //
                            bool continueIdle = false;

                            if (OleComponents != null) {
                                IEnumerator enumerator = OleComponents.Values.GetEnumerator();

                                while (enumerator.MoveNext()) {
                                    ComponentHashtableEntry idleEntry = (ComponentHashtableEntry)enumerator.Current;
                                    continueIdle |= idleEntry.component.FDoIdle(-1);
                                }
                            }

                            // give the component one more chance to terminate the
                            // message loop.
                            //
                            continueLoop = component.FContinueMessageLoop(reason, pvLoopData, null);

                            if (continueLoop) {
                                if (continueIdle) {
                                    // If someone has asked for idle time, give it to them.  However,
                                    // don't cycle immediately; wait up to 100ms.  Why?  Because we don't
                                    // want someone to attach to idle, forget to detach, and then ----
                                    // the CPU.  For Windows Forms this generally isn't an issue because
                                    // our component always returns false from its idle request
                                    UnsafeNativeMethods.MsgWaitForMultipleObjectsEx(0, IntPtr.Zero, 100, NativeMethods.QS_ALLINPUT, NativeMethods.MWMO_INPUTAVAILABLE);
                                }
                                else {
                                    // We should call GetMessage here, but we cannot because
                                    // the component manager requires that we notify the
                                    // active component before we pull the message off the
                                    // queue.  This is a bit of a problem, because WaitMessage
                                    // waits for a NEW message to appear on the queue.  If a
                                    // message appeared between processing and now WaitMessage
                                    // would wait for the next message.  We minimize this here
                                    // by calling PeekMessage.
                                    //
                                    if (!UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) {
                                        UnsafeNativeMethods.WaitMessage();
                                    }
                                }
                            }
                        }
                    }

                    Debug.Unindent();
                    Debug.WriteLineIf(CompModSwitches.MSOComponentManager.TraceInfo, "ComponentManager : message loop " + reason.ToString(CultureInfo.InvariantCulture) + " complete.");
                }
                finally {
                    currentState = currentLoopState;
                    this.activeComponent = prevActive;
                }

                return !continueLoop;
            }
        protected internal override bool ProcessMnemonic(char charCode) {
            bool processed = false;

            if (CanSelect) {
                try {
                    NativeMethods.tagCONTROLINFO ctlInfo = new NativeMethods.tagCONTROLINFO();
                    int hr = this.axOleControl.GetControlInfo(ctlInfo);
                    if (NativeMethods.Succeeded(hr)) {
                        //
                        // Sadly, we don't have a message so we must fake one ourselves.
                        // The message we are faking is a WM_SYSKEYDOWN with the right
                        // alt key setting.
                        NativeMethods.MSG msg = new NativeMethods.MSG();
                        msg.hwnd = IntPtr.Zero;
                        msg.message = NativeMethods.WM_SYSKEYDOWN;
                        msg.wParam = (IntPtr) Char.ToUpper(charCode, CultureInfo.CurrentCulture);
                        msg.lParam = (IntPtr) 0x20180001;
                        msg.time = SafeNativeMethods.GetTickCount();
                        NativeMethods.POINT p = new NativeMethods.POINT();
                        UnsafeNativeMethods.GetCursorPos(p);
                        msg.pt_x = p.x;
                        msg.pt_y = p.y;
                        if (SafeNativeMethods.IsAccelerator(new HandleRef(ctlInfo, ctlInfo.hAccel), ctlInfo.cAccel, ref msg, null)) {
                            this.axOleControl.OnMnemonic(ref msg);
                            FocusInternal();
                            processed = true;
                        }
                    }
                }
                catch (Exception ex) {
                    if (ClientUtils.IsCriticalException(ex)) {
                        throw;
                    }
                    Debug.Fail("error in processMnemonic");
                }
            }
            return processed;
        }
示例#33
0
            private bool LocalModalMessageLoop(Form form) {
                try {
                    // Execute the message loop until the active component tells us to stop.
                    //
                    NativeMethods.MSG msg = new NativeMethods.MSG();
                    bool unicodeWindow = false;
                    bool continueLoop = true;

                    while (continueLoop) {

                        bool peeked = UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE);

                        if (peeked) {

                            // If the component wants us to process the message, do it.
                            // The component manager hosts windows from many places.  We must be sensitive
                            // to ansi / Unicode windows here.
                            //
                            if (msg.hwnd != IntPtr.Zero && SafeNativeMethods.IsWindowUnicode(new HandleRef(null, msg.hwnd))) {
                                unicodeWindow = true;
                                if (!UnsafeNativeMethods.GetMessageW(ref msg, NativeMethods.NullHandleRef, 0, 0)) {
                                    continue;
                                }

                            }
                            else {
                                unicodeWindow = false;
                                if (!UnsafeNativeMethods.GetMessageA(ref msg, NativeMethods.NullHandleRef, 0, 0)) {
                                    continue;
                                }
                            }

                            if (!PreTranslateMessage(ref msg)) {
                                UnsafeNativeMethods.TranslateMessage(ref msg);
                                if (unicodeWindow) {
                                    UnsafeNativeMethods.DispatchMessageW(ref msg);
                                }
                                else {
                                    UnsafeNativeMethods.DispatchMessageA(ref msg);
                                }
                            }

                            if (form != null) {
                                continueLoop = !form.CheckCloseDialog(false);
                            }
                        }
                        else if (form == null) {
                            break;
                        }
                        else if (!UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE)) {
                            UnsafeNativeMethods.WaitMessage();
                        }
                    }
                    return continueLoop;
                }
                catch {
                    return false;
                }
            }
示例#34
0
        public static bool FilterMessage(ref Message message) {            

            bool modified;

            // Create copy of MSG structure
            NativeMethods.MSG msg = new NativeMethods.MSG();           
            msg.hwnd = message.HWnd;
            msg.message = message.Msg;
            msg.wParam = message.WParam;
            msg.lParam = message.LParam;

            bool processed = ThreadContext.FromCurrent().ProcessFilters(ref msg, out modified);
            if (modified) {
                message.HWnd = msg.hwnd;
                message.Msg = msg.message;
                message.WParam = msg.wParam;
                message.LParam = msg.lParam;
            }
            
            return processed;
        }
示例#35
0
        /// <include file='doc\TabControl.uex' path='docs/doc[@for="TabControl.WmTabBaseReLayout"]/*' />
        /// <devdoc>
        /// </devdoc>
        /// <internalonly/>
        private void WmTabBaseReLayout(ref Message m) {
            BeginUpdate();
            cachedDisplayRect = Rectangle.Empty;
            UpdateTabSelection(false);
            EndUpdate();
            Invalidate(true);

            // Remove other TabBaseReLayout messages from the message queue
            NativeMethods.MSG msg = new NativeMethods.MSG();
            IntPtr hwnd = Handle;
            while (UnsafeNativeMethods.PeekMessage(ref msg, new HandleRef(this, hwnd),
                                       tabBaseReLayoutMessage,
                                       tabBaseReLayoutMessage,
                                       NativeMethods.PM_REMOVE)) {
                ; // NULL loop
            }
        }
示例#36
0
 public static extern int DispatchMessage([In] ref NativeMethods.MSG msg);
示例#37
0
 public static extern bool IsAccelerator(HandleRef hAccel, int cAccelEntries, [In] ref NativeMethods.MSG lpMsg, short[] lpwCmd);
示例#38
0
 public static extern bool GetMessage([In, Out] ref NativeMethods.MSG msg, HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax);
示例#39
0
            /// <include file='doc\Application.uex' path='docs/doc[@for="Application.ComponentManager.UnsafeNativeMethods.IMsoComponentManager.FContinueIdle"]/*' />
            /// <devdoc>
            ///      Called periodically by a component during IMsoComponent::FDoIdle.
            ///      Return TRUE if component can continue its idle time processing,
            ///      FALSE if not (in which case component returns from FDoIdle.)
            /// </devdoc>
            bool UnsafeNativeMethods.IMsoComponentManager.FContinueIdle() {

                // Essentially, if we have a message on queue, then don't continue
                // idle processing.
                //
                NativeMethods.MSG msg = new NativeMethods.MSG();
                return !UnsafeNativeMethods.PeekMessage(ref msg, NativeMethods.NullHandleRef, 0, 0, NativeMethods.PM_NOREMOVE);
            }