public async Task <int> TranslateAcceleratorAsync(MSG msg) { var message = new Message { hwnd = msg.hwnd, message = (int)msg.message, wParam = msg.wParam, lParam = msg.lParam, time = (int)msg.time, pt_x = msg.pt.x, pt_y = msg.pt.y }; var used = ComponentDispatcher.RaiseThreadMessage(ref message); if (used) { msg.message = (uint)message.message; msg.wParam = message.wParam; msg.lParam = message.lParam; return(VSConstants.S_OK); } if (_propertyPageSite != null) { await _projectThreadingService.SwitchToUIThread(); return(_propertyPageSite.TranslateAccelerator(new MSG[] { msg })); } return(VSConstants.S_OK); }
void ProcessMessage(ref MSG msg, ref bool handled) { if (msg.message == 786) foreach (var Key in Keys) if (msg.wParam.ToInt32() == Key.Key) Key.Value(); }
public void HotKeyPressed(ref MSG msg, ref bool handled) { if (msg.message == 0x0312) { if (msg.wParam.ToInt32() == HOTKEY_1) { this.Data1.TimerStart(); } if (msg.wParam.ToInt32() == HOTKEY_2) { this.Data2.TimerStart(); } if (msg.wParam.ToInt32() == HOTKEY_3) { this.Data3.TimerStart(); } if (msg.wParam.ToInt32() == HOTKEY_4) { this.Data1.Reset(); this.Data2.Reset(); this.Data3.Reset(); } } }
public bool TranslateAccelerator(ref MSG msg) { var message = new Message { hwnd = msg.hwnd, message = (int)msg.message, wParam = msg.wParam, lParam = msg.lParam, time = (int)msg.time, pt_x = msg.pt.x, pt_y = msg.pt.y }; var used = ComponentDispatcher.RaiseThreadMessage(ref message); if (used) { msg.message = (uint)message.message; msg.wParam = message.wParam; msg.lParam = message.lParam; return(true); } return(false); }
private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled) { if (handled) return; if (msg.message != WmHotKey) return; HotKey hotKey; if (!DictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey)) return; hotKey.Action?.Invoke(hotKey); handled = true; }
public void HotKeyPressed(ref MSG msg, ref bool handled) { if (msg.message == 0x0312) { if (msg.wParam.ToInt32() == HOTKEY_1) { SetCursorPos(Settings1.Default.PosX, Settings1.Default.PosY); } } }
void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { if (msg.message == WM_HOTKEY) { if (ShortcutPressed != null) ShortcutPressed(this, EventArgs.Empty); handled = true; } else handled = false; }
/// <summary> /// Preprocess input (keyboard) messages in order to translate them to editor commands if they map. Since we are in a modal dialog /// we need to tell the shell to allow pre-translate during a modal loop as well as instructing it to use the editor keyboard scope /// even though, as far as the shell knows, there is no editor active (in a document or tool window, the shell knows nothing about /// random modal dialogs such as this one). /// </summary> private void FilterThreadMessage(ref System.Windows.Interop.MSG msg, ref bool handled) { if (msg.message >= WM_KEYFIRST && msg.message <= WM_KEYLAST) { IVsFilterKeys2 filterKeys = (IVsFilterKeys2)ServiceProvider.GlobalProvider.GetService(typeof(SVsFilterKeys)); Microsoft.VisualStudio.OLE.Interop.MSG oleMSG = new Microsoft.VisualStudio.OLE.Interop.MSG() { hwnd = msg.hwnd, lParam = msg.lParam, wParam = msg.wParam, message = (uint)msg.message }; //Ask the shell to do the command mapping for us and fire off the command if it succeeds with that mapping. We pass no 'custom' scopes //(third and fourth argument) because we pass VSTAEXF_UseTextEditorKBScope to indicate we want the shell to apply the text editor //command scope to this call. Guid cmdGuid; uint cmdId; int fTranslated; int fStartsMultiKeyChord; int res = filterKeys.TranslateAcceleratorEx(new Microsoft.VisualStudio.OLE.Interop.MSG[] { oleMSG }, (uint)(__VSTRANSACCELEXFLAGS.VSTAEXF_UseTextEditorKBScope | __VSTRANSACCELEXFLAGS.VSTAEXF_AllowModalState), 0 /*scope count*/, new Guid[0] /*scopes*/, out cmdGuid, out cmdId, out fTranslated, out fStartsMultiKeyChord); if (fStartsMultiKeyChord == 0) { //HACK: Work around a bug in TranslateAcceleratorEx that will report it DIDN'T do the command mapping //when in fact it did :( Problem has been fixed (since I found it while writing this code), but in the //mean time we need to successfully eat keystrokes that have been mapped to commands and dispatched, //we DON'T want them to continue on to Translate/Dispatch. "Luckily" asking TranslateAcceleratorEx to //do the mapping WITHOUT firing the command will give us the right result code to indicate if the command //mapped or not, unfortunately we can't always do this as it would break key-chords as it causes the shell //to not remember the first input match of a multi-part chord, hence the reason we ONLY hit this block if //it didn't tell us the input IS part of key-chord. res = filterKeys.TranslateAcceleratorEx(new Microsoft.VisualStudio.OLE.Interop.MSG[] { oleMSG }, (uint)(__VSTRANSACCELEXFLAGS.VSTAEXF_NoFireCommand | __VSTRANSACCELEXFLAGS.VSTAEXF_UseTextEditorKBScope | __VSTRANSACCELEXFLAGS.VSTAEXF_AllowModalState), 0, new Guid[0], out cmdGuid, out cmdId, out fTranslated, out fStartsMultiKeyChord); handled = (res == VSConstants.S_OK); return; } //We return true (that we handled the input message) if we managed to map it to a command OR it was the //beginning of a multi-key chord, anything else should continue on with normal processing. handled = ((res == VSConstants.S_OK) || (fStartsMultiKeyChord != 0)); } }
private void ThreadPreprocessMessageMethod(ref MSG msg, ref bool handled) { if (!handled) { if (msg.message == NativeMethods.WM_HOTKEY && (int)(msg.wParam) == _id) { OnHotKeyPressed(); handled = true; } } }
// HotKeyの動作を設定する public void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { // ホットキーを表すメッセージであるか否か if (msg.message != WM_HOTKEY) return; // 自分が登録したホットキーか否か var hotkeyID = msg.wParam.ToInt32(); if (!this._hotkeyEvents.Any((x) => x.Key == hotkeyID)) return; // 両方を満たす場合は登録してあるホットキーのイベントを実行 new ThreadStart( () => _hotkeyEvents[hotkeyID](this, EventArgs.Empty) ).Invoke(); }
bool OnWM_MESSAGE256(ref System.Windows.Interop.MSG msg, ref bool handled) { // // add extra variables to observe with Debugger // IntPtr HWND, WParam, LParam; HWND = msg.hwnd; WParam = msg.wParam; LParam = msg.lParam; this.txt_HWND.Text = HWND.ToString(); this.txt_WParam.Text = WParam.ToString(); this.txt_LParam.Text = LParam.ToString(); this.txt_KeyData.Text = KeyInterop.KeyFromVirtualKey(WParam.ToInt32()).ToString();//keyData.ToString(); return(true); }
private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { if (msg.message == WM_HOTKEY) { try { _callback(); } catch (Exception e) { Console.WriteLine(e); } handled = true; } }
void ComponentDispatcher_ThreadFilterMessage(ref System.Windows.Interop.MSG msg, ref bool handled) { switch (msg.message) { //这里只能以 INPUT 来截取,不支持 KEYDOWN 来截取,不然后面的 RawInput 获取值的时候无效 case Win32.WM_INPUT: { // Should never get here if you are using PreMessageFiltering KeyPressEvent keyPressEvent; _keyboardDriver.ProcessRawInput(msg.lParam, out keyPressEvent); if (KeyInterop.KeyFromVirtualKey(keyPressEvent.VKey) == Key.Enter) { _isMonitoring = false; Btn_OK.IsEnabled = true; } // 回车 作为结束标志 if (_isMonitoring && keyPressEvent.KeyPressState == "BREAK") { //存储 Win32 按键的int值 int key = keyPressEvent.VKey; byte[] state = new byte[256]; Win32.GetKeyboardState(state); _eventQ.Enqueue(new RawInput_dll.Win32.KeyAndState(key, state)); } if (_isMonitoring == false) { str_ScanGunID = keyPressEvent.DeviceName; } } break; //这里截获这个消息有问题,替代方法是放到 WndProc 中去获取 case Win32.WM_USB_DEVICECHANGE: { } break; default: break; } return; }
public void Run() { var msg = new MSG(); while (true) { if (!GetMessage(ref msg, IntPtr.Zero, 0, 0)) { break; } if (msg.message == WM_QUIT) break; User32Native.TranslateMessage(ref msg); User32Native.DispatchMessage(ref msg); } }
void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { if (msg.message == WM_HOTKEY) { if (_mainWindow.WindowState == WindowState.Normal) { _mainWindow.WindowState = WindowState.Minimized; } else { _mainWindow.Show(); if (_mainWindow.WindowState == WindowState.Minimized) { _mainWindow.WindowState = WindowState.Normal; } _mainWindow.Activate(); } } }
// ****************************************************************** private static void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled) { if (!handled) { if (msg.message == WmHotKey) { HotKey hotKey; if (_dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey)) { if (hotKey.Action != null) { hotKey.Action.Invoke(hotKey); } handled = true; } } } }
/// <summary> /// Called when the message pump receives a keyboard message. /// </summary> /// <param name="msg">A structure with the message data.</param> /// <param name="handled"> /// <see langword="true"/> if the message was handled; otherwise, <see langword="false"/>. /// </param> private static void OnThreadFilterMessage(ref Message msg, ref bool handled) { if (Form == null) { return; } // Forward keyboard messages to the message loop of the game window. If they // are not forwarded, XNA Keyboard class will not detect keypresses when the // WPF window is active. // To forward the messages to WinForms, we could also call // System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(wpfWindow); // This forwards the same keyboard messages, except the mouse wheel message. int message = msg.message; if (message == WindowMessages.WM_KEYDOWN || message == WindowMessages.WM_KEYUP || message == WindowMessages.WM_CHAR || message == WindowMessages.WM_DEADCHAR || message == WindowMessages.WM_SYSKEYDOWN || message == WindowMessages.WM_SYSKEYUP || message == WindowMessages.WM_SYSCHAR || message == WindowMessages.WM_SYSDEADCHAR || message == WindowMessages.WM_MOUSEWHEEL #if MONOGAME || message == WindowMessages.WM_MOUSEMOVE || message == WindowMessages.WM_LBUTTONDOWN || message == WindowMessages.WM_LBUTTONUP || message == WindowMessages.WM_LBUTTONDBLCLK || message == WindowMessages.WM_MBUTTONDOWN || message == WindowMessages.WM_MBUTTONUP || message == WindowMessages.WM_MBUTTONDBLCLK || message == WindowMessages.WM_RBUTTONDOWN || message == WindowMessages.WM_RBUTTONUP || message == WindowMessages.WM_RBUTTONDBLCLK #endif ) { NativeMethods.PostMessage(Handle, msg.message, msg.wParam, msg.lParam); } }
protected override bool TranslateAcceleratorCore(ref System.Windows.Interop.MSG msg, ModifierKeys mod) { if (msg.message is Api.WM_KEYDOWN or Api.WM_SYSKEYDOWN) { var key = (KKey)msg.wParam; switch ((key, mod)) { case (KKey.C, ModifierKeys.Control): ZCopy(); return(true); case (KKey.V, ModifierKeys.Control): ZPaste(); return(true); case (KKey.F12, 0): Menus.Edit.Go_to_definition(); return(true); default: if (_ImageDeleteKey(key)) { return(true); } if (CodeInfo.SciCmdKey(this, key, mod)) { return(true); } switch ((key, mod)) { case (KKey.Enter, 0): case (KKey.Enter, ModifierKeys.Control | ModifierKeys.Shift): zAddUndoPoint(); break; } break; } } return(base.TranslateAcceleratorCore(ref msg, mod)); }
private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { var now = DateTime.UtcNow.Ticks; if (msg.message != WM_HOTKEY) return; handled = true; if (now - _lastTickHotkeyWasPressed > _ticksToConsiderHotKeyTrigger) { _lastTickHotkeyWasPressed = now; return; } _lastTickHotkeyWasPressed = now; try { _callback(); } catch (Exception e) { Console.WriteLine(e); } }
/// <summary> /// Called by the WebOC whenever its IOleInPlaceActiveObject::TranslateAccelerator() is called. /// See also the IOleControlSite.TranslateAccelerator() implementation here. /// </summary> int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref System.Windows.Interop.MSG msg, ref Guid group, int nCmdID) { // // Returning S_FALSE will allow the native control to do default processing, // i.e., execute the shortcut key. Returning S_OK will cancel the shortcut key. /* WebBrowser wb = (WebBrowser)this.Host; * * if (!wb.WebBrowserShortcutsEnabled) * { * int keyCode = (int)msg.wParam | (int)Control.ModifierKeys; * * if (msg.message != WindowMessage.WM_CHAR * && Enum.IsDefined(typeof(Shortcut), (Shortcut)keyCode)) { * return NativeMethods.S_OK; * } * return NativeMethods.S_FALSE; * } */ return(NativeMethods.S_FALSE); }
static void Main(string[] args) { Mapper.Init(); var messageContainer = MessageModelsHelper.GetMessageContainer(); var window = SystemMessageSender.FindWindow(null, Constants.WindowName); //Thread.Sleep(5000); //SystemMessageSender.ShowWindowAsync(window, 9); //restore //Console.WriteLine("restored window"); //Thread.Sleep(5000); Thread.Sleep(10000); foreach (var msg in messageContainer.Msgs) { //SystemMessageSender.PostMessage((IntPtr)msg.Hwnd, msg.Message, (int)msg.WParam, (int)msg.LParam); //var m = AutoMapper.Mapper.Map<MSG>(msg); Thread.Sleep(10); var rmsg = new MSG() { hwnd = window, lParam = msg.lParam, message = msg.message, wParam = msg.wParam, time = msg.time, pt_x = msg.pt_x, pt_y = msg.pt_y }; var result2 = SystemMessageSender.PostMessage(window, rmsg.message, rmsg.wParam, rmsg.lParam); //if (rmsg.message != 15) //{ // var result2 = SystemMessageSender.TranslateMessage(ref rmsg); //} } }
public int TranslateAccelerator(VsMsg[] pMsg) { if (pMsg == null || pMsg.Length == 0) { throw new ArgumentNullException(nameof(pMsg)); } var xMsg = pMsg[0]; var xMessage = new Message(); xMessage.hwnd = xMsg.hwnd; xMessage.message = (int)xMsg.message; xMessage.wParam = xMsg.wParam; xMessage.lParam = xMsg.lParam; xMessage.time = (int)xMsg.time; xMessage.pt_x = xMsg.pt.x; xMessage.pt_y = xMsg.pt.y; var xUsed = ComponentDispatcher.RaiseThreadMessage(ref xMessage); if (xUsed) { xMsg.message = (uint)xMessage.message; xMsg.wParam = xMessage.wParam; xMsg.lParam = xMessage.lParam; return(VSConstants.S_OK); } int xResult = 0; if (mPropertyPageSite != null) { ProjectThreadingService.SwitchToUIThread(); xResult = mPropertyPageSite.TranslateAccelerator(pMsg); } return(xResult); }
public bool PreFilterMessage(ref SWF.Message msg) { if (_window == null || !_window.IsActive) { return(false); } switch (msg.Msg) { case NativeMethods.WM_KEYDOWN: //0x100 case NativeMethods.WM_KEYUP: //0x101 case NativeMethods.WM_CHAR: //0x102 case NativeMethods.WM_DEADCHAR: //0x103 case NativeMethods.WM_SYSKEYDOWN: //0x104 case NativeMethods.WM_SYSKEYUP: //0x105 case NativeMethods.WM_SYSCHAR: //0x106 case NativeMethods.WM_SYSDEADCHAR: //0x107 if (!_inPreFilterMessage) { _inPreFilterMessage = true; try { SW.Interop.MSG msg2 = Convert.ToSystemWindowsInteropMSG(msg); bool fReturn = SW.Interop.ComponentDispatcher.RaiseThreadMessage(ref msg2); return(fReturn); } finally { _inPreFilterMessage = false; } } return(false); default: return(false); } }
void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled) { if (msg.message == NativeMethods.WM_KEYDOWN) { Modifiers = Modifiers | ModifierForVK((Keys)msg.wParam); } if (msg.message == NativeMethods.WM_KEYUP) { Keys upKey = (Keys)msg.wParam; ModifierKeys mods = ModifierForVK(upKey); if (mods != ModifierKeys.None) { Modifiers = Modifiers & ~ModifierForVK(upKey); } else if (upKey != Keys.None) { Key = upKey; DispatcherTimer minizeTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 250), DispatcherPriority.Normal, TimedClose, Dispatcher); minizeTimer.Start(); } } HotKeyDescription = KeyboardEmulator.ModifierKeysToString(Modifiers) + Key.ToString(); }
void ComponentDispatcher_ThreadFilterMessage(ref System.Windows.Interop.MSG msg, ref bool handled) { switch (msg.message) { case Win32.WM_INPUT: { // Should never get here if you are using PreMessageFiltering _keyboardDriver.ProcessRawInput(msg.lParam); this.OnWM_MESSAGE256(ref msg, ref handled); //handled = } break; case WM_USB_DEVICECHANGE: { Debug.WriteLine("USB Device Arrival / Removal"); _keyboardDriver.EnumerateDevices(); } break; default: break; } return; }
// Delegate IKeyboardInputSink calls to the hosted HwndSource. protected override sealed bool TranslateAcceleratorCore(ref MSG msg, ModifierKeys modifiers) { if (_hwndSource != null) { HwndSourceHostRoot root = (HwndSourceHostRoot)_hwndSource.RootVisual; Debug.Assert(root.IsLogicalParentEnabled); root.IsLogicalParentEnabled = false; try { return ((IKeyboardInputSink)_hwndSource).TranslateAccelerator(ref msg, modifiers); } finally { root.IsLogicalParentEnabled = true; } } else { return base.TranslateAcceleratorCore(ref msg, modifiers); } }
/// <summary> /// 系统消息处理函数 /// </summary> /// <param name="msg"></param> /// <param name="handled"></param> private void MessageFilter(ref System.Windows.Interop.MSG msg, ref bool handled) { //1:让TWAIN进行消息处理 TwainCommand cmd = twSession.PassMessageWPF(ref msg); messageLogger.Debug("TWAIN 信息 = " + cmd + ":" + DateTime.Now); if (cmd == TwainCommand.Not || cmd == TwainCommand.Null) // 非数据源消息 { handled = false; // 消息未处理,由窗口过程处理 return; } //2:进行消息处理 switch (cmd) { case TwainCommand.CloseRequest: { configFlag = false; EndingScan(); twSession.DisableDS(); break; } case TwainCommand.CloseOk: { configFlag = true; EndingScan(); twSession.DisableDS(); break; } case TwainCommand.DeviceEvent: { break; } //扫描仪传输就绪函数 case TwainCommand.TransferReady: { loadAndUnloadLogger.Debug("TWAIN 信息 = TransferReady " + DateTime.Now); ScanImageViewer scanViewer = null; try { if (ShowProgress) { //方式一:启动文件传输,弹出进度提示对话框 //获得文件格式 CapInfo capInfo; capInfo = twSession.GetScannerCap(TwCap.ICAP_IMAGEFILEFORMAT); string intStr = capInfo.CurrentIntStr; string enumStr = twSession.ConvertIntStringToEnumString(TwCap.ICAP_IMAGEFILEFORMAT, intStr); TwFileFormat fileFormat = (TwFileFormat)Enum.Parse(typeof(TwFileFormat), enumStr); //获取分辨率 capInfo = twSession.GetScannerCap(TwCap.ICAP_XRESOLUTION); Int32 resolution = Int32.Parse(capInfo.CurrentIntStr); // 获得空白页检测阈值 capInfo = twSession.GetScannerCap(TwCap.ICAP_AUTODISCARDBLANKPAGES); intStr = capInfo.CurrentIntStr; int blankImageSizeThreshold = 0; if (!Int32.TryParse(intStr, out blankImageSizeThreshold)) { blankImageSizeThreshold = 0; } scanViewer = new ScanImageViewer(twSession, userConfig.MaxSize, blankImageSizeThreshold, resolution, fileFormat); //生成显示控件对象 scanViewer.StartTransfer(); //开始图像传输 scanViewer.ShowDialog(); //展示显示控件 scanResultList = scanViewer.ScanFileNames; //获取文件传输过程中的列表 } else { //方式二:设置鼠标为等待状态,在相同线程中启动文件传输 Mouse.OverrideCursor = Cursors.Wait; TransferFiles(); } //发出扫描完成事件 logger.Debug("扫描完成 :" + DateTime.Now); RoutedEventArgs scanArgs = new RoutedEventArgs(ScanCompletedEvent); RaiseEvent(scanArgs); break; } catch (Exception e) { logger.Error("在MessageFilter中发生异常,异常信息; " + e.Message); } finally { if (scanViewer != null) { logger.Debug("关闭扫描仪。"); scanViewer.Close(); } //结束扫描 logger.Debug("结束扫描,使DS变为非使能状态。"); EndingScan(); twSession.DisableDS(); if (!ShowProgress) { //将鼠标复位 Mouse.OverrideCursor = null; } } break; } default: break; } handled = true; }
void ThreadPreprocessMessage(ref MSG msg, ref bool handled) { var id = msg.wParam.ToInt32(); if (msg.message == 0x0312 && msg.hwnd == handle) { // ID = mod * 1000 + key // Key = ID / modifier * 1000 var str = id.ToString(); var key = str.Length > 4 ? id / (int.Parse(str.Substring(0, 1)) * 1000) : id; // Fire event because a key was captured by the handler // Whether it's registered or not OnKeyCaptured(KeyInterop.KeyFromVirtualKey(key)); // Only handle if this key is registered if (Hotkeys.ContainsKey(id)) { var _hotkey = Hotkeys[id]; _hotkey.Method.Invoke(_hotkey.Parameter); } } }
protected virtual bool OnMnemonicCore(ref MSG msg, ModifierKeys modifiers) { return false; }
bool IKeyboardInputSink.OnMnemonic(ref MSG msg, ModifierKeys modifiers) { return OnMnemonicCore(ref msg, modifiers); }
private static extern int ForwardTranslateAccelerator(ref MSG pMsg, bool appUnhandled);
public static bool RaiseThreadMessage(ref MSG msg) { ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData; return(data.RaiseThreadMessage(ref msg)); }
int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref MSG msg, int grfModifiers) { // Handle tabbing out of the WebOC if ((WindowMessage)msg.message == WindowMessage.WM_KEYDOWN && (int)msg.wParam == NativeMethods.VK_TAB) { FocusNavigationDirection direction = (grfModifiers & 1/*KEYMOD_SHIFT*/) != 0 ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next; // For the WebOCHostedInBrowserProcess case, we need to switch to the right thread. Host.Dispatcher.Invoke( DispatcherPriority.Send, new SendOrPostCallback(MoveFocusCallback), direction); return NativeMethods.S_OK; } return NativeMethods.S_FALSE; }
internal IntPtr FilterMessage(IntPtr hwnd, WindowMessage message, IntPtr wParam, IntPtr lParam, ref bool handled) { IntPtr result = IntPtr.Zero; // It is possible to be re-entered during disposal. Just return. if (null == _source || null == _source.Value) { return(result); } _msgTime = 0; try { _msgTime = SafeNativeMethods.GetMessageTime(); } catch (System.ComponentModel.Win32Exception) { System.Diagnostics.Debug.WriteLine("HwndKeyboardInputProvider: GetMessageTime failed!"); } switch (message) { // WM_KEYDOWN is sent when a nonsystem key is pressed. // A nonsystem key is a key that is pressed when the ALT key // is not pressed. // WM_SYSKEYDOWN is sent when a system key is pressed. case WindowMessage.WM_SYSKEYDOWN: case WindowMessage.WM_KEYDOWN: { // If we have a IKeyboardInputSite, then we should have already // called ProcessKeyDown (from TranslateAccelerator) // But there are several paths (our message pump / app's message // pump) where we do (or don't) call through IKeyboardInputSink. // So the best way is to just check here if we already did it. if (_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam)) { break; } // We will use the current time before generating KeyDown events so we can filter // the later posted WM_CHAR. int currentTime = 0; try { currentTime = SafeNativeMethods.GetTickCount(); } catch (System.ComponentModel.Win32Exception) { System.Diagnostics.Debug.WriteLine("HwndMouseInputProvider: GetTickCount failed!"); } // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS // In case a nested message pump is used before we return // from processing this message, we disable processing the // next WM_CHAR message because if the code pumps messages // it should really mark the message as handled. HwndSource._eatCharMessages = true; DispatcherOperation restoreCharMessages = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new DispatcherOperationCallback(HwndSource.RestoreCharMessages), null); // Force the Dispatcher to post a new message to service any // pending operations, so that the operation we just posted // is guaranteed to get dispatched after any pending WM_CHAR // messages are dispatched. Dispatcher.CriticalRequestProcessing(true); MSG msg = new MSG(hwnd, (int)message, wParam, lParam, _msgTime, 0, 0); ProcessKeyAction(ref msg, ref handled); if (!handled) { // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS // We did not handle the WM_KEYDOWN, so it is OK to process WM_CHAR messages. // We can also abort the pending restore operation since we don't need it. HwndSource._eatCharMessages = false; restoreCharMessages.Abort(); } // System.Console.WriteLine("KEYDOWN(message={0}, wParam={1})={2}", message, wParam, handled); } break; // WM_KEYUP is sent when a nonsystem key is released. // A nonsystem key is a key that is pressed when the ALT key // is not pressed. // WM_SYSKEYUP is sent when a system key is released. case WindowMessage.WM_SYSKEYUP: case WindowMessage.WM_KEYUP: { if (_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam)) { break; } MSG msg = new MSG(hwnd, (int)message, wParam, lParam, _msgTime, 0, 0); ProcessKeyAction(ref msg, ref handled); // System.Console.WriteLine("KEYUP (message={0}, wParam={1})={2}", message, wParam, handled); } break; // WM_UNICHAR (UTF-32) support needs to be implemented // case WindowMessage.WM_UNICHAR: case WindowMessage.WM_CHAR: case WindowMessage.WM_DEADCHAR: case WindowMessage.WM_SYSCHAR: case WindowMessage.WM_SYSDEADCHAR: { if (_source.Value.IsRepeatedKeyboardMessage(hwnd, (int)message, wParam, lParam)) { break; } // MITIGATION: HANDLED_KEYDOWN_STILL_GENERATES_CHARS if (HwndSource._eatCharMessages) { break; } ProcessTextInputAction(hwnd, message, wParam, lParam, ref handled); // System.Console.WriteLine("CHAR(message={0}, wParam={1})={2}", message, wParam, handled); } break; case WindowMessage.WM_EXITMENULOOP: case WindowMessage.WM_EXITSIZEMOVE: { // MITIGATION: KEYBOARD_STATE_OUT_OF_SYNC // // Avalon relies on keeping it's copy of the keyboard // state. This is for a number of reasons, including that // we need to be able to give this state to worker threads. // // There are a number of cases where Win32 eats the // keyboard messages, and this can cause our keyboard // state to become stale. Obviously this can happen when // another app is in the foreground, but we handle that // by re-synching our keyboard state when we get focus. // // Other times are when Win32 enters a nested loop. While // any one could enter a nested loop at any time for any // reason, Win32 is nice enough to let us know when it is // finished with the two common loops: menus and sizing. // We re-sync our keyboard device in response to these. // if (_active) { _partialActive = true; ReportInput(hwnd, InputMode.Foreground, _msgTime, RawKeyboardActions.Activate, 0, false, false, 0); } } break; // WM_SETFOCUS is sent immediately after focus is granted. // This is our clue that the keyboard is active. case WindowMessage.WM_SETFOCUS: { OnSetFocus(hwnd); handled = true; } break; // WM_KILLFOCUS is sent immediately before focus is removed. // This is our clue that the keyboard is inactive. case WindowMessage.WM_KILLFOCUS: { if (_active && wParam != _source.Value.CriticalHandle) { // Console.WriteLine("WM_KILLFOCUS"); if (_source.Value.RestoreFocusMode == RestoreFocusMode.Auto) { // when the window that's acquiring focus (wParam) is // a descendant of our window, remember the immediate // child so that we can restore focus to it. _restoreFocusWindow = GetImmediateChildFor((IntPtr)wParam, _source.Value.CriticalHandle); _restoreFocus = null; // If we aren't restoring focus to a child window, // then restore focus to the element that currently // has WPF keyboard focus if it is directly in this // HwndSource. if (_restoreFocusWindow == IntPtr.Zero) { DependencyObject focusedDO = Keyboard.FocusedElement as DependencyObject; if (focusedDO != null) { HwndSource hwndSource = PresentationSource.CriticalFromVisual(focusedDO) as HwndSource; if (hwndSource == _source.Value) { _restoreFocus = focusedDO as IInputElement; } } } } PossiblyDeactivate((IntPtr)wParam); } handled = true; } break; // WM_UPDATEUISTATE is sent when the user presses ALT, expecting // the app to display accelerator keys. We don't always hear the // keystroke - another message loop may handle it. So report it // here. case WindowMessage.WM_UPDATEUISTATE: { RawUIStateInputReport report = new RawUIStateInputReport(_source.Value, InputMode.Foreground, _msgTime, (RawUIStateActions)NativeMethods.SignedLOWORD((int)wParam), (RawUIStateTargets)NativeMethods.SignedHIWORD((int)wParam)); _site.Value.ReportInput(report); handled = true; } break; } if (handled && EventTrace.IsEnabled(EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info)) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientInputMessage, EventTrace.Keyword.KeywordInput | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Info, Dispatcher.GetHashCode(), hwnd.ToInt64(), message, (int)wParam, (int)lParam); } return(result); }
protected virtual new bool TranslateCharCore(ref MSG msg, System.Windows.Input.ModifierKeys modifiers) { return default(bool); }
bool IKeyboardInputSink.TranslateChar(ref MSG msg, ModifierKeys modifiers) { return TranslateCharCore(ref msg, modifiers); }
protected virtual new bool OnMnemonicCore(ref MSG msg, System.Windows.Input.ModifierKeys modifiers) { return default(bool); }
protected virtual bool TranslateCharCore(ref MSG msg, ModifierKeys modifiers) { return false; }
protected override bool TranslateAcceleratorCore(ref MSG msg, ModifierKeys modifiers) { SyncUIActiveState(); Invariant.Assert(ActiveXState >= ActiveXHelper.ActiveXState.UIActive, "Should be at least UIActive when we are processing accelerator keys"); return (ActiveXInPlaceActiveObject.TranslateAccelerator(ref msg) == 0); }
private void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled) { if (!handled) { if (msg.message == WmHotKey) { HotKey hotKey; if (dictHotKeyToCalBackProc.TryGetValue((int)msg.wParam, out hotKey)) { if (Activated != null) Activated.Invoke(); handled = true; } } } }
public static bool RaiseThreadMessage(ref MSG msg) { ComponentDispatcherThread data = ComponentDispatcher.CurrentThreadData; return data.RaiseThreadMessage(ref msg); }
// Delegate IKeyboardInputSink calls to the hosted HwndSource. protected override sealed bool OnMnemonicCore(ref MSG msg, ModifierKeys modifiers) { if (_hwndSource != null) { return ((IKeyboardInputSink)_hwndSource).OnMnemonic(ref msg, modifiers); } else { return base.OnMnemonicCore(ref msg, modifiers); } }
private void ComponentDispatcherThreadFilterMessage(ref MSG msg, ref bool handled) { //_messageContainer.Msgs.Add(msg); var msgId = msg.message; if (Enum.GetValues(typeof(MessageType)).Cast<MessageType>().Any(x => (int)x == msgId)) { Debug.WriteLine("ComponentDispatcherThreadFilterMessage"); Debug.WriteLine((MessageType)msgId); } }
// Delegate IKeyboardInputSink calls to the hosted HwndSource. protected override sealed bool TranslateCharCore(ref MSG msg, ModifierKeys modifiers) { if (_hwndSource != null) { return ((IKeyboardInputSink)_hwndSource).TranslateChar(ref msg, modifiers); } else { return base.TranslateCharCore(ref msg, modifiers); } }
string getString(MSG m) { return string.Format("hwnd: {0:X4}\t message: {1:X4}\t Wparam: {2:X4}\t Lparam: {3:X4}", m.hwnd, m.message, m.wParam, m.lParam); }
private static extern bool PeekMessage(out System.Windows.Interop.MSG msg_0, IntPtr intptr_1, uint uint_0, uint uint_1, uint uint_2);
void ComponentDispatcher_ThreadFilterMessage(ref System.Windows.Interop.MSG msg, ref bool handled) { switch (msg.message) { //这里只能以 INPUT 来截取,不支持 KEYDOWN 来截取,不然后面的 RawInput 获取值的时候无效 case Win32.WM_INPUT: { // Should never get here if you are using PreMessageFiltering KeyPressEvent keyPressEvent; _keyboardDriver.ProcessRawInput(msg.lParam, out keyPressEvent); textBox_ScanGunInfoNow.Text = keyPressEvent.DeviceName; //只处理一次事件,不然有按下和弹起事件 if (keyPressEvent.KeyPressState == "MAKE" && keyPressEvent.DeviceName == str_ScanGunID && str_ScanGunID != string.Empty) { textBox_Output.Focus(); //找到结尾标志的时候,就不加入队列了,然后就发送到界面上赋值 if (KeyInterop.KeyFromVirtualKey(keyPressEvent.VKey) == Key.Enter) { _isMonitoring = false; string str_Out = string.Empty; ThreadPool.QueueUserWorkItem((o) => { while (_eventQ.Count > 0) { RawInput_dll.Win32.KeyAndState keyAndState = _eventQ.Dequeue(); str_Out += CalibrationScanGun.Chr(keyAndState.Key).ToString(); System.Threading.Thread.Sleep(5); // might need adjustment } Application.Current.Dispatcher.BeginInvoke((Action)(() => { textBox_Output.Text = str_Out; })); _eventQ.Clear(); _isMonitoring = true; }); } // 回车 作为结束标志 if (_isMonitoring) { //存储 Win32 按键的int值 int key = keyPressEvent.VKey; byte[] state = new byte[256]; Win32.GetKeyboardState(state); _eventQ.Enqueue(new RawInput_dll.Win32.KeyAndState(key, state)); } } } break; case Win32.WM_KEYDOWN: { KeyPressEvent keyPressEvent; _keyboardDriver.ProcessRawInput(msg.lParam, out keyPressEvent); if (keyPressEvent.DeviceName == str_ScanGunID && str_ScanGunID != string.Empty) { handled = true; } } break; //这里截获这个消息有问题,替代方法是放到 WndProc 中去获取 case Win32.WM_USB_DEVICECHANGE: { } break; default: break; } return; }