protected override void WndProc(ref System.Windows.Forms.Message m) { if (!(m.Msg == WM_SETFOCUS || m.Msg == WM_ENABLE || m.Msg == WM_SETCURSOR)) { base.WndProc(ref m); } }
/// <summary> /// Preprocess input (keyboard) messages in order to translate them to editor commands if they map. Since our tool window is NOT an /// editor the shell won't consider the editor keybindings when doing its usual input pre-translation. We could either set our /// window frames InheritKeyBindings property to point to the std editor factory GUID OR we can do this. I chose this method as /// it allows us to have the editor keybindings active ONLY when the focus is in the editor, that way we won't have editor /// keybindings active in our window UNLESS the editor has focus, which is what we want. /// </summary> protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { //Only try and pre-process keyboard input messages, all others are not interesting to us. if (m.Msg >= WM_KEYFIRST && m.Msg <= WM_KEYLAST) { //Only attempt to do the input -> command mapping if focus is inside our hosted editor. if (this.control.IsKeyboardFocusWithin) { IVsFilterKeys2 filterKeys = (IVsFilterKeys2)GetService(typeof(SVsFilterKeys)); MSG oleMSG = new MSG() { hwnd = m.HWnd, lParam = m.LParam, wParam = m.WParam, message = (uint)m.Msg }; //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 MSG[] { oleMSG }, (uint)(__VSTRANSACCELEXFLAGS.VSTAEXF_UseTextEditorKBScope), 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 MSG[] { oleMSG }, (uint)(__VSTRANSACCELEXFLAGS.VSTAEXF_NoFireCommand | __VSTRANSACCELEXFLAGS.VSTAEXF_UseTextEditorKBScope), 0, new Guid[0], out cmdGuid, out cmdId, out fTranslated, out fStartsMultiKeyChord); return(res == VSConstants.S_OK); } //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. return((res == VSConstants.S_OK) || (fStartsMultiKeyChord != 0)); } } return(base.PreProcessMessage(ref m)); }
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData) { if (keyData == System.Windows.Forms.Keys.Left) { yaw += -5 * deg2rad; this.Invalidate(); return(true); } if (keyData == System.Windows.Forms.Keys.Right) { yaw += 5 * deg2rad; this.Invalidate(); return(true); } if (keyData == System.Windows.Forms.Keys.Up) { pitch += 5 * deg2rad; this.Invalidate(); return(true); } if (keyData == System.Windows.Forms.Keys.Down) { pitch += -5 * deg2rad; this.Invalidate(); return(true); } return(base.ProcessCmdKey(ref msg, keyData)); }
/// <summary> /// 接收的到数据 /// </summary> /// <param name="m"></param> /// <returns></returns> public static string Receive(ref System.Windows.Forms.Message m) { COPYDATASTRUCT cds = new COPYDATASTRUCT(); Type cdsType = cds.GetType(); cds = (COPYDATASTRUCT)m.GetLParam(cdsType); return cds.lpData; }
protected override void WndProc(ref System.Windows.Forms.Message msg) { const int WM_POINTERDOWN = 0x0246; const int WM_POINTERUP = 0x247; const int WM_LBUTTONDOWN = 0x201; const int WM_LBUTTONUP = 0x202; const int WM_MOUSEMOVE = 0x200; switch (msg.Msg) { case WM_LBUTTONDOWN: Debug.WriteLine("DOWN"); if (_first) { this.baseColor = this.BackColor; _first = false; } this.BackColor = Color.Red; this.ButtonTouchDownEvent(this, new EventArgs()); break; case WM_LBUTTONUP: Debug.WriteLine("UP"); this.BackColor = this.baseColor; this.ButtonTouchUpEvent(this, new EventArgs()); break; } base.WndProc(ref msg); }
/// <summary> /// ウィンドウメッセージ処理 /// </summary> /// <param name="m">メッセージ情報</param> protected override void WndProc(ref System.Windows.Forms.Message m) { // HSCROLL/VSCROLLメッセージに対してもHScroll()/VScroll()イベント実行 switch (m.Msg) { case (int)Utility.Windows.WM.HSCROLL: base.OnHScroll(System.EventArgs.Empty); break; case (int)Utility.Windows.WM.VSCROLL: base.OnVScroll(System.EventArgs.Empty); break; case (int)Utility.Windows.WM.SETFOCUS: // 選択不可能の場合はSETFOCUSメッセージを無視させる if (!this.m_boSelectable) { return; } break; default: break; } base.WndProc(ref m); }
public override void ProcessWindowMessage(ref System.Windows.Forms.Message m) { if (m.Msg == msgID_CBT_HookReplaced) { RaiseEvent(HookReplaced, EventArgs.Empty); } else if (m.Msg == msgID_CBT_Activate) { RaiseEvent(WindowActivated, new WindowEventArgs(m.WParam)); } else if (m.Msg == msgID_CBT_CreateWnd) { RaiseEvent(WindowCreated, new WindowEventArgs(m.WParam)); } else if (m.Msg == msgID_CBT_DestroyWnd) { RaiseEvent(WindowDestroyed, new WindowEventArgs(m.WParam)); } else if (m.Msg == msgID_CBT_MinMax) { RaiseEvent(MinMax, new SysCommandEventArgs(m.WParam, m.LParam)); } else if (m.Msg == msgID_CBT_MoveSize) { RaiseEvent(MoveSize, new WindowEventArgs(m.WParam)); } else if (m.Msg == msgID_CBT_SetFocus) { RaiseEvent(SetFocus, new WindowEventArgs(m.WParam)); } else if (m.Msg == msgID_CBT_SysCommand) { RaiseEvent(SysCommand, new SysCommandEventArgs(m.WParam, m.LParam)); } }
public override void ProcessWindowMessage(ref System.Windows.Forms.Message m) { //string dbgMessage = ""; if (m.Msg == _msgIdGetMsg) { //if (m.LParam.ToInt64() == NativeConstants.WM_SYSCOMMAND) //{ // dbgMessage = string.Format("WM_SYSCOMMAND, GetMsg, Handle = {0}", m.WParam); // System.Diagnostics.Trace.WriteLine(dbgMessage); //} _cacheHandle = m.WParam; _cacheMessage = m.LParam; } else if (m.Msg == _msgIdGetMsgParams) { if (GetMsg != null && _cacheHandle != IntPtr.Zero && _cacheMessage != IntPtr.Zero) { //if (cacheMessage.ToInt64() == NativeConstants.WM_SYSCOMMAND) //{ // dbgMessage = string.Format("WM_SYSCOMMAND, GetMsgParams, Handle = {0}, WParam = {1}", cacheHandle, m.WParam); // System.Diagnostics.Trace.WriteLine(dbgMessage); //} RaiseEvent(GetMsg, new WndProcEventArgs(_cacheHandle, _cacheMessage, m.WParam, m.LParam)); } _cacheHandle = IntPtr.Zero; _cacheMessage = IntPtr.Zero; } }
/// <summary> /// 解析消息 /// </summary> /// <param name="msg"></param> /// <returns></returns> public bool DoMessage(ref System.Windows.Forms.Message msg) { bool tested = false; switch (msg.Msg) { case Win32Message.WM_COPYDATA: DoMsgCopyData(ref msg); tested = true; break; case WM_USER_START: DoMsgStart(ref msg); tested = true; break; case WM_USER_CONTINUE: DoMsgContinue(ref msg); tested = true; break; case WM_USER_ABORT: DoMsgAbort(ref msg); tested = true; break; default: break; } return(tested); }
/// <summary> /// 处理拷贝数据 /// </summary> /// <param name="msg"></param> /// <returns></returns> public bool DoMsgCopyData(ref System.Windows.Forms.Message msg) { bool tested = false; if (tetsingEnable) { try { Win32Message.COPYDATASTRUCT mystr = new Win32Message.COPYDATASTRUCT(); Type mytype = mystr.GetType(); mystr = (Win32Message.COPYDATASTRUCT)msg.GetLParam(mytype); Byte[] scriptbytes = new Byte[mystr.cbData]; Marshal.Copy(mystr.lpData, scriptbytes, 0, mystr.cbData); System.Text.Encoding utf8 = System.Text.Encoding.UTF8; testingScript = utf8.GetString(scriptbytes); System.Windows.Forms.MessageBox.Show(testingScript); tested = true; } catch { tested = false; } } return(tested); }
private void ednw_EventHandler(ref System.Windows.Forms.Message m, ref bool handled) { if (!createEvents) { return; } if (m.Msg == MM_MIXM_CONTROL_CHANGE && m.WParam == hMixer) { int ctrlID = m.LParam.ToInt32(); MixerControl c = FindControl(ctrlID); if (c != null) { if (ControlChanged != null) { ControlChanged(this, new MixerEventArgs(this, c.Line, c)); } c.OnChanged(); } } else if (m.Msg == MM_MIXM_LINE_CHANGE && m.WParam == hMixer) { int lineID = m.LParam.ToInt32(); MixerLine l = FindLine(lineID); if (l != null) { if (ControlChanged != null) { LineChanged(this, new MixerEventArgs(this, l, null)); } l.OnChanged(); } } }
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { System.Windows.Forms.Message m = new System.Windows.Forms.Message(); m.HWnd = hwnd; m.Msg = msg; m.WParam = wParam; m.LParam = lParam; if (handled) { return(IntPtr.Zero); } if (msg == App.WM_CHECK_MERCHANT_INFO_Expired) { if (m_nExpiredMonth >= 3) { try { string strMessage = String.Format((string)this.FindResource("ResStr_The_agent_information_hasn_t_updated_for_____months__please_update_online_"), m_nExpiredMonth); VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, this, strMessage, (string)this.FindResource("ResStr_Warning")); } catch { } } } return(IntPtr.Zero); }
private static bool DispatchSystemCommandMessage(ref System.Windows.Forms.Message m, TaskbarWindow taskbarWindow) { if (m.Msg == (int)WindowMessage.SystemCommand) { if (((int)m.WParam) == TabbedThumbnailNativeMethods.ScClose) { // Raise the event if (taskbarWindow.TabbedThumbnail.OnTabbedThumbnailClosed()) { // Remove the taskbar window from our internal list if (_taskbarWindowList.Contains(taskbarWindow)) { _taskbarWindowList.Remove(taskbarWindow); } taskbarWindow.Dispose(); taskbarWindow = null; } } else if (((int)m.WParam) == TabbedThumbnailNativeMethods.ScMaximize) { // Raise the event taskbarWindow.TabbedThumbnail.OnTabbedThumbnailMaximized(); } else if (((int)m.WParam) == TabbedThumbnailNativeMethods.ScMinimize) { // Raise the event taskbarWindow.TabbedThumbnail.OnTabbedThumbnailMinimized(); } return(true); } return(false); }
public void onKeyEnter(ref System.Windows.Forms.Message m) { if (KeyEnter != null) { KeyEnter(this, ref m); } }
// Note: // - Subclass of ElementHost designed to work around focus problems with ElementHost. protected override void WndProc(ref System.Windows.Forms.Message m) { base.WndProc(ref m); if (m.Msg == Win32.WM_SETFOCUS) { var old_handle = m.WParam; // Get the handle to the child WPF element that we are hosting // After that get the next and previous items that would fall before // and after the WPF control in the tools->options page tabbing order if (PresentationSource.FromVisual(Child) is HwndSource source && old_handle != IntPtr.Zero) { var next_tab_element = GetNextFocusElement(source.Handle, forward: true); var prev_tab_element = GetNextFocusElement(source.Handle, forward: false); var root_element = source.RootVisual as UIElement; // If we tabbed back from the next element then set focus to the last item if (root_element != null && next_tab_element == old_handle) { root_element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Last)); } // If we tabbed in from the previous element then set focus to the first item else if (root_element != null && prev_tab_element == old_handle) { root_element.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); } } } }
protected override void WndProc(ref System.Windows.Forms.Message m) { base.WndProc(ref m); //***TODO*** //Draw Shapes on scroll }
private static bool DispatchSystemCommandMessage(ref System.Windows.Forms.Message m, TaskbarWindow taskbarWindow) { if (m.Msg == (int)WindowMessage.SystemCommand) { if (((int)m.WParam) == (int)SystemMenuCommands.Close) // Raise the event if (taskbarWindow.TabbedThumbnail.OnTabbedThumbnailClosed()) { // Remove the taskbar window from our internal list if (_taskbarWindowList.Contains(taskbarWindow)) _ = _taskbarWindowList.Remove(taskbarWindow); taskbarWindow.Dispose(); taskbarWindow = null; } else if (((uint)m.WParam) == (uint)SystemMenuCommands.Maximize) // Raise the event taskbarWindow.TabbedThumbnail.OnTabbedThumbnailMaximized(); else if (((uint)m.WParam) == (uint)SystemMenuCommands.Minimize) // Raise the event taskbarWindow.TabbedThumbnail.OnTabbedThumbnailMinimized(); return true; } return false; }
/// <summary> /// Processes window message and indicates wether it is a twain event or not /// </summary> /// <param name="m">Message send to the application</param> /// <returns>The translates TwainMessage if suitable</returns> internal Messages ProcessMessage(ref System.Windows.Forms.Message m) { Messages result = Messages.Null; if (dataSource.IsOpen) { int pos = User32.GetMessagePos(); windowsMessage.hwnd = m.HWnd; windowsMessage.message = m.Msg; windowsMessage.wParam = m.WParam; windowsMessage.lParam = m.LParam; windowsMessage.time = User32.GetMessageTime(); windowsMessage.pt_x = (short)pos; windowsMessage.pt_y = (short)(pos >> 16); Marshal.StructureToPtr(windowsMessage, interopStruct.WindowsMessagePointer, false); interopStruct.Message = 0; ReturnCodes rc = Twain32.ProcessMessage(dataSourceManager.Identity, dataSource.Identity, ref interopStruct); if (rc == ReturnCodes.DataSourceEvent) { result = (Messages)interopStruct.Message; } } return(result); }
public static void OnDeviceChange(System.Windows.Forms.Message m) { if (m.Msg == WM_DEVICECHANGE) { var lpdb = (DEV_BROADCAST_HDR)m.GetLParam(typeof(DEV_BROADCAST_HDR)); if ((DeviceChangeEvent)m.WParam.ToInt32() == DeviceChangeEvent.DBT_DEVICEREMOVECOMPLETE) { if (lpdb.dbchDeviceType == DeviceChangeType.DBT_DEVTYP_PORT) { string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_HDR)))); var handler = ListChanged; if (handler != null) { handler(null, new SerialPortListChangedEventArgs(portName, SerialPortListAction.Removed)); } } } else if ((DeviceChangeEvent)m.WParam.ToInt32() == DeviceChangeEvent.DBT_DEVICEARRIVAL) { if (lpdb.dbchDeviceType == DeviceChangeType.DBT_DEVTYP_PORT) { string portName = Marshal.PtrToStringUni((IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(typeof(DEV_BROADCAST_HDR)))); var handler = ListChanged; if (handler != null) { handler(null, new SerialPortListChangedEventArgs(portName, SerialPortListAction.Added)); } } } } }
protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { ThreadHelper.ThrowIfNotOnUIThread(); if (m.Msg >= WM_KEYFIRST && m.Msg <= WM_KEYLAST) { var oleMsg = new MSG { hwnd = m.HWnd, lParam = m.LParam, wParam = m.WParam, message = (uint)m.Msg }; if (_filterKeys == null) { _filterKeys = this.GetService <IVsFilterKeys2, SVsFilterKeys>(); } return(_filterKeys.TranslateAcceleratorEx( new[] { oleMsg }, (uint)__VSTRANSACCELEXFLAGS.VSTAEXF_UseTextEditorKBScope, 0, Array.Empty <Guid>(), out var _, out var _, out var _, out var _) == VSConstants.S_OK); } return(base.PreProcessMessage(ref m)); }
private static void DispatchTaskbarButtonMessages(ref System.Windows.Forms.Message m, TaskbarWindow taskbarWindow) { if (m.Msg == (int)TaskbarNativeMethods.WmTaskbarButtonCreated) { AddButtons(taskbarWindow); } else { if (!_buttonsAdded) { AddButtons(taskbarWindow); } if (m.Msg == TaskbarNativeMethods.WmCommand && CoreNativeMethods.GetHiWord(m.WParam.ToInt64(), 16) == ThumbButton.Clicked) { var buttonId = CoreNativeMethods.GetLoWord(m.WParam.ToInt64()); var buttonsFound = from b in taskbarWindow.ThumbnailButtons where b.Id == buttonId select b; foreach (var button in buttonsFound) { button.FireClick(taskbarWindow); } } } }
/// <summary> /// PreProcessMessage override. /// </summary> protected override bool PreProcessMessage(ref System.Windows.Forms.Message m) { bool wasHandled = base.PreProcessMessage(ref m); if (!wasHandled) { if ((m.Msg == Microsoft.VisualStudioTools.Project.NativeMethods.WM_SYSKEYDOWN && (int)m.WParam == Microsoft.VisualStudioTools.Project.NativeMethods.VK_DOWN) || (m.Msg == Microsoft.VisualStudioTools.Project.NativeMethods.WM_KEYDOWN && ((int)m.WParam == Microsoft.VisualStudioTools.Project.NativeMethods.VK_ESCAPE || (int)m.WParam == Microsoft.VisualStudioTools.Project.NativeMethods.VK_F2 || // F2 key (int)m.WParam == Microsoft.VisualStudioTools.Project.NativeMethods.VK_DELETE || (int)m.WParam == Microsoft.VisualStudioTools.Project.NativeMethods.VK_TAB || ((int)m.WParam == (int)System.Windows.Forms.Keys.C && (Keyboard.Modifiers & ModifierKeys.Control) != 0)))) // Cntrl-C { // By default, when ESC is pressed and a document is open in the editor, VS tool windows will respond // by switching focus to the document and the ESC keypress does not get propagated to the WPF handlers. // Override this behavior checking to see if WPF can handle the event here and letting VS take over if it can't. // Additionally, by default when TAB is pressed, VS will try to interpret this as the editor command to tab-in code // if editor commands are inherited. Let WPF get a first-pass at this to try to tab to the next focused item. var interopMsg = Utilities.ConvertToInteropMsg(m); wasHandled = System.Windows.Interop.ComponentDispatcher.RaiseThreadMessage(ref interopMsg); } } return(wasHandled); }
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { System.Windows.Forms.Message m = System.Windows.Forms.Message.Create(hwnd, msg, wParam, lParam); if (m.Msg != ProcessInterop.WM_COPYDATA) { return(IntPtr.Zero); } // Get the CopyDataStruct struct from lParam. CopyDataStruct cds = (CopyDataStruct)m.GetLParam(typeof(CopyDataStruct)); if (cds.cbData == Marshal.SizeOf(typeof(FilePathStruct))) { // If the size matches { // Marshal the data from the unmanaged memory block to a FilePathStruct managed struct. FilePathStruct filePathStruct = (FilePathStruct)Marshal.PtrToStructure(cds.lpData, typeof(FilePathStruct)); OpenFile(filePathStruct.FilePath); if (this.Owner.WindowState == WindowState.Minimized) { this.Owner.WindowState = WindowState.Normal; } this.Owner.Activate(); // Bring the Gherkin window to the foreground and activates it. } } return(IntPtr.Zero); }
private static void DispatchTaskbarButtonMessages(ref System.Windows.Forms.Message m, TaskbarWindow taskbarWindow) { if (m.Msg == (int)Win32Native.Taskbar.Taskbar.WmTaskbarButtonCreated) AddButtons(taskbarWindow); else { if (!_buttonsAdded) AddButtons(taskbarWindow); if (m.Msg == (int)WindowMessage.Command && Core.GetHiWord(m.WParam.ToInt64(), 16) == ThumbButton.Clicked) { int buttonId = Core.GetLoWord(m.WParam.ToInt64()); IEnumerable<ThumbnailToolBarButton> buttonsFound = from b in taskbarWindow.ThumbnailButtons where b.Id == buttonId select b; foreach (ThumbnailToolBarButton button in buttonsFound) button.FireClick(taskbarWindow); } } }
public void ReceiverHandleMsg(ref System.Windows.Forms.Message msg) { foreach (MsgReceiverInterface rev in receiverList) { rev.HandleMsg(ref msg); } }
/// <summary> /// WndProc /// </summary> /// <param name="m"></param> protected override void WndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case 0x00f: //wm_paint if (m_bPaint) { base.WndProc(ref m); } else { m.Result = IntPtr.Zero; } break; case 0x102: //wm_char base.WndProc(ref m); break; default: base.WndProc(ref m); break; } }
protected override void WndProc(ref System.Windows.Forms.Message m) { if (m.Msg == WM_LBUTTONDOWN) // left mouse button down { // get the current position of the mouse pointer Point mousePos = Control.MousePosition; // get the node the user clicked on TreeNode testNode = GetNodeAt(PointToClient(mousePos)); // see if the clicked area contained an actual node if (testNode != null) { // A node was clicked, so raise our custom event var e = new TreeNodeMouseClickEventArgs(testNode, MouseButtons.Left, 1, mousePos.X, mousePos.Y); if (CustomNodeClick != null) { CustomNodeClick(this, e); } } } // call through to let the base class process the message base.WndProc(ref m); }
void clipboardEventHandler(ref System.Windows.Forms.Message m, ref bool handled) { if (handled) { return; } if (m.Msg == WM_DRAWCLIPBOARD) { // notify me if (ClipboardChanged != null) { ClipboardChanged(this, EventArgs.Empty); } // pass on message SendMessage(nextHWnd, m.Msg, m.WParam, m.LParam); handled = true; } else if (m.Msg == WM_CHANGECBCHAIN) { if (m.WParam == nextHWnd) { nextHWnd = m.LParam; } else { SendMessage(nextHWnd, m.Msg, m.WParam, m.LParam); } } }
public void WndProc(System.Windows.Forms.Message m) { if (m.Msg == 0x3D1) { RaiseVolumeChanged(); } }
protected override void WndProc(ref System.Windows.Forms.Message m) { // This all helps to prevent scrolling or refreshing the text window // while we're parsing for color, parenthesis, etc. if (this._parsing) { if (m.Msg == (int)Win32Messages.WM_VSCROLL || m.Msg == (int)Win32Messages.WM_HSCROLL) { return; } else if (m.Msg == (int)Win32Messages.EM_LINESCROLL || m.Msg == (int)Win32Messages.EM_SCROLL || m.Msg == (int)Win32Messages.EM_SCROLLCARET) { return; } else if (m.Msg == (int)Win32Messages.WM_PAINT || m.Msg == (int)Win32Messages.WM_NCPAINT) { return; } else if (m.Msg == (int)Win32Messages.WM_ERASEBKGND) { return; } } base.WndProc(ref m); }
/// <summary> /// Converts AtfMessage to WfMessage</summary> /// <param name="msg">AtfMessage</param> /// <returns>WfMessage</returns> public static WfMessage ToWf(AtfMessage msg) { var newMsg = new WfMessage(); newMsg.HWnd = msg.Result; newMsg.Msg = msg.Msg; newMsg.WParam = msg.WParam; newMsg.LParam = msg.LParam; newMsg.Result = msg.Result; return newMsg; }
protected override void WndProc(ref Message m) { switch (m.Msg) { case VSConstants.CPPM_CLEARSELECTION: HandleClearSelection(m); break; case VSConstants.CPPM_GETSELECTION: HandleGetSelection(m); break; case VSConstants.CPPM_INITIALIZELIST: HandleInitializeItems(m); break; case VSConstants.CPPM_INITIALIZETAB: HandleInitializeTab(m); break; case VSConstants.CPPM_QUERYCANSELECT: HandleQueryCanSelect(m); break; case VSConstants.CPPM_SETMULTISELECT: HandleSetMultiSelect(m); break; case UnsafeNativeMethods.WM_SIZE: HandleWmSize(m); break; default: base.WndProc(ref m); break; } }
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == UnsafeNativeMethods.WM_MOVING || msg == UnsafeNativeMethods.WM_SIZING) { var m = new System.Windows.Forms.Message { HWnd = hwnd, Msg = msg, WParam = wParam, LParam = lParam, Result = IntPtr.Zero }; UnsafeNativeMethods.ReDrawWindow(m); handled = true; } if (msg == UnsafeNativeMethods.WM_MOUSEACTIVATE) { handled = true; return new IntPtr(UnsafeNativeMethods.MA_NOACTIVATE); } return IntPtr.Zero; }
/// <summary> /// Constructor with Windows message</summary> /// <param name="msg">Windows message</param> public MessageInterop(WfMessage msg) : this(msg.HWnd, msg.Msg, msg.WParam, msg.LParam, msg.Result) { }
private void HandleQueryCanSelect(Message m) { if (m.LParam != IntPtr.Zero) Marshal.WriteByte(m.LParam, (byte)(CanSelectItems ? 1 : 0)); }
protected override void WndProc(ref Message m) { if (!this.enabled) { base.WndProc(ref m); return; } switch ((WM)m.Msg) { case WM.SYSCOMMAND: #if SSL_DEBUG_PRINT Console.WriteLine("{0} syscmd {1} {2}", DateTime.Now.ToLongTimeString(), base.Handle, (SC)m.WParam); #endif switch ((SC)m.WParam) { case SC.SCREENSAVE: if (null != this.ScreenSaverRaising) { CancelEventArgs cea = new CancelEventArgs(); this.ScreenSaverRaising(this, cea); if (cea.Cancel) { return; } } break; } break; } base.WndProc(ref m); }
private void HandleSetMultiSelect(Message m) { SetSelectionMode(Convert.ToBoolean((byte)m.LParam)); }
private void HandleWmSize(Message m) { if (m.WParam.ToInt32() == UnsafeNativeMethods.SIZE_RESTORED) { int newSize = m.LParam.ToInt32(); short newWidth = (short)newSize; short newHeight = (short)(newSize >> 16); this.Size = new Size(newWidth, newHeight); UnsafeNativeMethods.SetWindowPos(UnsafeNativeMethods.GetParent(Handle), IntPtr.Zero, 0, 0, newWidth, newHeight, 0); PerformLayout(); Invalidate(true); } }
private void HandleClearSelection(Message m) { ClearSelection(); }
private void HandleGetSelection(Message m) { ComponentSelectorData[] items = GetSelection(); int count = items != null ? items.Length : 0; Marshal.WriteInt32(m.WParam, count); if (count > 0) { IntPtr ppItems = Marshal.AllocCoTaskMem(count * Marshal.SizeOf(typeof(IntPtr))); for (int i = 0; i < count; i++) { IntPtr pItem = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(VSCOMPONENTSELECTORDATA))); Marshal.WriteIntPtr(ppItems, i * IntPtr.Size, pItem); VSCOMPONENTSELECTORDATA data = new VSCOMPONENTSELECTORDATA() { dwSize = (uint)Marshal.SizeOf(typeof(VSCOMPONENTSELECTORDATA)), bstrFile = items[i].File, bstrTitle = items[i].Title, bstrProjRef = items[i].ProjectReference, guidTypeLibrary = items[i].TypeLibrary, lCustom = items[i].CustomInformation, type = items[i].ComponentType, // the following items are handled separately lcidTypeLibrary = 0, wFileBuildNumber = 0, wFileMajorVersion = 0, wFileMinorVersion = 0, wFileRevisionNumber = 0, wTypeLibraryMajorVersion = 0, wTypeLibraryMinorVersion = 0, }; if (items[i].TypeLibraryCulture != null) { data.lcidTypeLibrary = (uint)items[i].TypeLibraryCulture.LCID; } if (items[i].FileVersion != null) { data.wFileMajorVersion = (ushort)items[i].FileVersion.Major; data.wFileMinorVersion = (ushort)items[i].FileVersion.Minor; data.wFileBuildNumber = (ushort)items[i].FileVersion.Build; data.wFileRevisionNumber = (ushort)items[i].FileVersion.Revision; } if (items[i].TypeLibraryVersion != null) { data.wTypeLibraryMajorVersion = (ushort)items[i].TypeLibraryVersion.Major; data.wTypeLibraryMinorVersion = (ushort)items[i].TypeLibraryVersion.Minor; } Marshal.StructureToPtr(data, pItem, false); } Marshal.WriteIntPtr(m.LParam, ppItems); } }
protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e) { base.OnKeyUp(e); if (e.KeyCode == System.Windows.Forms.Keys.Enter) { #region ENTER Key try { if (!e.SuppressKeyPress) { // If the user just pressed the "Enter" key, we want to tab in the // new line to match any whitespace from the previous line. int prevLn = this.GetLineFromCharIndex(this.SelectionStart); string prevTxt = this.Lines[prevLn - 1]; string prevWs = string.Empty; if (prevTxt.StartsWith("\t") || prevTxt.StartsWith(" ")) prevWs = prevTxt.Substring(0, prevTxt.Length - prevTxt.TrimStart('\t', ' ').Length); // After a return keypress, we're always on a "new" line, so if we // find any whitespace on the previous line, just send a // simulated windows msg to make the control think the user pressed // the keys to recreate that whitespace on this line. // Using this method of simulating the keypress prevents having to // "color parse" the entire text which is required if we manually // change the control's "Text" property. if (!string.IsNullOrEmpty(prevWs)) { char[] wsChars = prevWs.ToCharArray(); for (int i = 0; i < wsChars.Length; i++) { System.Windows.Forms.Message msg = new System.Windows.Forms.Message(); msg.Msg = (int)Win32Messages.WM_CHAR; msg.HWnd = new IntPtr(5572486); if (wsChars[i] == '\t') { msg.WParam = new IntPtr(9); msg.LParam = new IntPtr(983041); } else if (wsChars[i] == ' ') { msg.WParam = new IntPtr(32); msg.LParam = new IntPtr(3735553); IntPtr tst = new IntPtr(); } else throw new Exception("Unexpected whitespace character encountered."); this.WndProc(ref msg); } } } } catch { // This isn't important enough to let it throw errors, // especially since I added the WndProc fake keypress. } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Space) { #region SPACE Key - This is all handled in a join ENTER/SPACE clause in the "KeyDown" handler. //// NOTE: This occurs *after* the space character has already been //// processed! //if (this._autoCompMenu != null && this._autoCompMenu.SelectedIndex > -1) //{ // try // { // // If the AutoComplete list is open and has an item selected, // // we need to insert the selected text instead of // // inserting the space. // this.SuspendRefresh(); // this._parsing = true; // int selStart = this.SelectionStart, // selLength = this.SelectionLength, // dotIdx = this.Text.Substring(0, this.SelectionStart + this.SelectionLength).LastIndexOf('.'); // this.Select(dotIdx, selStart + selLength - dotIdx); // this.SelectedText = string.Format(".[{0}] ", this._autoCompMenu.Items[this._autoCompMenu.SelectedIndex].ToString()); // } // finally // { // this._parsing = false; // this.ResumeRefresh(); // } //} //this.EndAutoComplete(); #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.OemPeriod || e.KeyCode == System.Windows.Forms.Keys.Decimal) { #region PERIOID Key if (this._autoComp && !string.IsNullOrEmpty(this._connStr)) { int iSelStart = this.SelectionStart, // We have to be concious of the fact that, however unlikely, // it's possible for a query to have a qualifier as the // very first thing in the text box. iSpcIdx = System.Math.Max(this.Text.Substring(0, iSelStart).LastIndexOfAny(new char[] { ' ', '[', '(', ',', '\n', '\t' }), 0); string sQualNm = this.Text.Substring(iSpcIdx, iSelStart - iSpcIdx).TrimStart(' ', '[', '(', ',', '\n', '\t').TrimEnd('.', ' ', ']'); if (this._autoCompleteSchemas.Contains(sQualNm)) { try { using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(this._connStr)) { conn.Open(); if (conn.State != System.Data.ConnectionState.Open) throw new Exception(); List<string> tbls = new List<string>(); int icStart = this._connStr.IndexOf('=', this._connStr.ToLower().IndexOf("initial catalog=")) + 1, icEnd = this._connStr.IndexOf(';', icStart), icLen = (icEnd > -1) ? icEnd - icStart : this._connStr.Length - icStart; if (icStart > -1) { // Get the database name from the connection string. string databasename = this._connStr.Substring(icStart, icLen); // Get the tables and views. using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(string.Format("SELECT (su.name + '.' + so.name) as [name] FROM sys.sysobjects so INNER JOIN sys.schemas su ON su.schema_id = so.uid WHERE (xtype=N'U' OR xtype=N'V') AND su.name = '{1}' ORDER BY so.name", databasename, sQualNm), conn)) using (System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader()) while (rdr.Read()) tbls.Add(rdr[0].ToString()); // Get the stored proceedures. using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(string.Format("SELECT (su.name + '.' + so.name + ' SP') as [name] FROM sys.sysobjects so INNER JOIN sys.schemas su ON su.schema_id = so.uid WHERE xtype=N'P' AND su.name = '{1}' AND (so.name NOT IN ('sp_upgraddiagrams', 'sp_renamediagram', 'sp_helpdiagrams', 'sp_helpdiagramdefinition', 'sp_dropdiagram', 'sp_creatediagram', 'sp_alterdiagram') OR OBJECT_ID(N'dbo.sysdiagrams') IS NULL) ORDER BY so.name", databasename, sQualNm), conn)) using (System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader()) while (rdr.Read()) tbls.Add(rdr[0].ToString()); // Get the functions. using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(string.Format("SELECT (su.name + '.' + so.name + '()') as [name] FROM sys.sysobjects so INNER JOIN sys.schemas su ON su.schema_id = so.uid WHERE xtype=N'FN' AND su.name = '{1}' AND (so.name <> 'fn_diagramobjects' OR OBJECT_ID(N'dbo.sysdiagrams') IS NULL) ORDER BY so.name", databasename, sQualNm), conn)) using (System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader()) while (rdr.Read()) tbls.Add(rdr[0].ToString()); } if (tbls.Count > 0) this.ShowAutoComplete(tbls.ToArray(), AutoCompleteType.Table); } } catch { // We don't want this actually throwing exceptions. If // and error occurs, we'll just ignore it and give up. } } else { // Check to see if the list of table aliases has been populated. //if (this._refTablesAlias.Count < 1) this.ParseTables(); string tblKey = string.Empty; if (this._refTablesAlias.ContainsKey(sQualNm)) tblKey = this._refTablesAlias[sQualNm]; else if (this._refTables.Contains(sQualNm)) tblKey = sQualNm; if (string.IsNullOrEmpty(tblKey)) // We don't have a reference to this table name or alias. return; try { if (this._refTablesCols[tblKey] == null) { // If there's no column set stored, then we have to try and // retreive the table's columns. string connStr = this._connStr + ((this._connStr.EndsWith(";")) ? "" : ";"), instanceNm = string.Empty, dbNm = string.Empty, schemaNm = string.Empty, tblNm = string.Empty; // Determine the values for the table/schema/instance names. string[] tblVals = tblKey.Split(new char[] { '.' }, StringSplitOptions.None); int iCatSt = connStr.ToLower().IndexOf("initial catalog="); switch (tblVals.Length) { case 1: // There's only a table name. dbNm = ((iCatSt < 0) ? "master" : connStr.Substring(connStr.IndexOf('=', iCatSt) + 1, connStr.IndexOf(';', iCatSt) - (connStr.IndexOf('=', iCatSt) + 1))); schemaNm = "dbo"; tblNm = tblVals[0]; break; case 2: // There's a schema and table name. dbNm = ((iCatSt < 0) ? "master" : connStr.Substring(connStr.IndexOf('=', iCatSt) + 1, connStr.IndexOf(';', iCatSt) - (connStr.IndexOf('=', iCatSt) + 1))); schemaNm = ((string.IsNullOrEmpty(tblVals[0])) ? "dbo" : tblVals[0]); tblNm = tblVals[1]; break; case 3: // There's database, schema and table name. dbNm = ((string.IsNullOrEmpty(tblVals[0])) ? ((iCatSt < 0) ? "master" : connStr.Substring(connStr.IndexOf('=', iCatSt) + 1, connStr.IndexOf(';', iCatSt) - (connStr.IndexOf('=', iCatSt) + 1))) : tblVals[0]); schemaNm = ((string.IsNullOrEmpty(tblVals[1])) ? "dbo" : tblVals[1]); tblNm = tblVals[2]; break; case 4: // There's an instance, database, schema and table name. int iDsBrk = connStr.IndexOf(';', connStr.ToLower().IndexOf("data source=")); dbNm = ((string.IsNullOrEmpty(tblVals[1])) ? ((iCatSt < 0) ? "master" : connStr.Substring(connStr.IndexOf('=', iCatSt) + 1, connStr.IndexOf(';', iCatSt) - (connStr.IndexOf('=', iCatSt) + 1))) : tblVals[1]); schemaNm = ((string.IsNullOrEmpty(tblVals[2])) ? "dbo" : tblVals[2]); tblNm = tblVals[3]; connStr = connStr.Substring(0, iDsBrk) + "/" + tblVals[0] + connStr.Substring(iDsBrk); break; } using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr)) { conn.Open(); using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT @@VERSION", conn)) if (!cmd.ExecuteScalar().ToString().ToLower().StartsWith("microsoft sql")) throw new Exception("The auto-complete feature requires a connection to a Microsoft SQL Server instance."); string qryCols = string.Format("SELECT sc.Name FROM [{0}].[sys].[syscolumns] sc INNER JOIN [{0}].[sys].[sysobjects] so ON sc.id = so.id AND so.id = (SELECT so2.id FROM [{0}].[sys].[sysobjects] so2 INNER JOIN [{0}].[sys].[schemas] su2 ON su2.schema_id = so2.uid AND su2.name = '{2}' WHERE so2.name = '{1}') ORDER BY sc.Name", dbNm, tblNm, schemaNm); using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(qryCols, conn)) using (System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader()) { if (rdr.HasRows) { string colNms = ""; while (rdr.Read()) { colNms += "|" + rdr.GetString(0); } colNms = colNms.TrimStart('|'); this._refTablesCols.Add(colNms, tblKey); } } } } if (this._refTablesCols[tblKey] != null) { string[] cols = this._refTablesCols[tblKey].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); this.ShowAutoComplete(cols, AutoCompleteType.Field); #region Moved to Independant Method ////Point csrLoc = this.PointToScreen(this.GetPositionFromCharIndex(this.SelectionStart)); //Point csrLoc = this.GetPositionFromCharIndex(this.SelectionStart); //if (this._autoCompMenu != null) // this._autoCompMenu.Dispose(); //this._autoCompStart = this.SelectionStart; //this._autoCompLine = this.CurrentLine; //int mnuLocY = csrLoc.Y; //string[] cols = this._refTablesCols[tblKey].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); //this._autoCompMenu = new System.Windows.Forms.ListBox(); //this.Controls.Add(this._autoCompMenu); //this._autoCompMenu.IntegralHeight = true; //this._autoCompMenu.Height = (int)Math.Min(cols.Length, 20) * (this._autoCompMenu.ItemHeight + 1); //if (mnuLocY + this._autoCompMenu.Height > this.Bottom) // mnuLocY = csrLoc.Y - this._autoCompMenu.Font.Height - this._autoCompMenu.Height; //else // mnuLocY += this._autoCompMenu.Font.Height; //this._autoCompMenu.Location = new Point(csrLoc.X, mnuLocY); //string longestWord = ""; //for (int i = 0; i < cols.Length; i++) //{ // this._autoCompMenu.Items.Add(cols[i]); // if (cols[i].Length > longestWord.Length) // longestWord = cols[i]; //} //using (Graphics g = this._autoCompMenu.CreateGraphics()) // this._autoCompMenu.Width = (int)Math.Ceiling(g.MeasureString("W" + longestWord, this._autoCompMenu.Font).Width) + 18; //this._autoCompMenu.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; //this._autoCompMenu.ScrollAlwaysVisible = true; //this._autoCompMenu.Cursor = System.Windows.Forms.Cursors.Arrow; //this._autoCompMenu.Click += new EventHandler(this.autoCompMenu_ItemClicked); //this._autoCompMenu.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.autoCompMenu_KeyPress); //this._autoCompMenu.Show(); #endregion } } catch { // I don't want this feature throwing errors, but if // something goes wrong, we'll just reset the system. this.EndAutoComplete(); this._refTables.Clear(); this._refTablesAlias.Clear(); this._refTablesCols.Clear(); this.ParseTables(); } } } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Escape) { #region ESCAPE Key this.EndAutoComplete(); #endregion } else if ((int)e.KeyCode == 219 && this._connStr.IndexOf("provider=microsoft") > -1 && this._connStr.ToLower().IndexOf("extended properties=excel") > -1) { #region Open Bracket // If we're working on an excel file, then when the user hits the // 'Open Bracket' key, we want popup a list of all the sheets // in the Excel file. #endregion } else if (e.KeyValue == 45) { #region INSERT Key this._insMode = !this._insMode; this.OnInsertModeChanged(EventArgs.Empty); #endregion } else if (e.KeyData != System.Windows.Forms.Keys.Shift && this.IsInputKey(e.KeyData) && !e.Control && !e.Alt) { #region Any Other Input Character if (this._autoCompMenu != null) { if ((e.KeyValue >= 65 && e.KeyValue <= 90) || e.KeyValue == 189) { // If the AutoComplete menu is open, we want to try // and select a menu item that matches what we're // typing. int iStPos = this.Text.Substring(0, this.SelectionStart).LastIndexOf('.'); if (iStPos < 0) // If we can't figure out which period ('.') to start from, // then just abort the whole thing. return; string sSrchText = this.Text.Substring(iStPos, this.SelectionStart - iStPos).TrimStart('.', '[').TrimEnd(']').ToLower(); for (int i = 0; i < this._autoCompMenu.Items.Count; i++) { string acSrchVal = string.Empty; // The logic differs at this point, depending on whether // we're searching for a field or table name. if (this._autoCompMenu.Tag.ToString() == "Table") { // Search for table name. string acItemVal = this._autoCompMenu.Items[i].ToString().ToLower(); acSrchVal = acItemVal.Substring(acItemVal.IndexOf('.') + 1); } else { acSrchVal = this._autoCompMenu.Items[i].ToString().ToLower(); } if (acSrchVal.StartsWith(sSrchText)) { this._autoCompMenu.SelectedIndex = i; this.Focus(); break; } else if (this._autoCompMenu.SelectedIndex > -1) this._autoCompMenu.ClearSelected(); } } } //else //{ // if (_autoComp && this._connStr != null) // { // // If the user is just straight typing, we want to check to see // // if what they are typing matches anything in the autocomplete // // lists. // int iSelStart = this.SelectionStart, // // We have to be concious of the fact that, however unlikely, // // it's possible for a query to have a qualifier as the // // very first thing in the text box. // iSpcIdx = Math.Max(this.Text.Substring(0, iSelStart).LastIndexOfAny(new char[] { ' ', '[', '(', ',', '\n', '\t' }), 0); // string sQualNm = this.Text.Substring(iSpcIdx, iSelStart - iSpcIdx).TrimStart(' ', '[', '(', ',', '\n', '\t').TrimEnd('.', ' ', ']'); // List<String> autoCompleteItems = new List<string>(); // if (this._autoCompleteSchemas != null) // for (int i = 0; i < this._autoCompleteSchemas.Count; i++) // if (this._autoCompleteSchemas[i].ToLower().StartsWith(sQualNm.ToLower())) // autoCompleteItems.Add(this._autoCompleteSchemas[i]); // if (this._autoCompleteTables != null) // for (int i = 0; i < this._autoCompleteTables.Count; i++) // if (this._autoCompleteTables[i].ToLower().StartsWith(sQualNm.ToLower())) // autoCompleteItems.Add(this._autoCompleteTables[i]); // if (this._refTablesCols != null) // for (int i = 0; i < this._refTablesCols.Count; i++) // if (this._refTablesCols[i].ToLower().StartsWith(sQualNm.ToLower())) // autoCompleteItems.Add(this._refTablesCols[i]); // if (autoCompleteItems.Count > 0) // this.ShowAutoComplete(autoCompleteItems.ToArray(), AutoCompleteType.Table); // } //} try { if (this.Text.Length > 0 && this.Lines[this.CurrentLine].Length > 0) this.ParseCurrentLine(); } catch { } #endregion } //if (this._addToSel > 0) // this.Select(this.SelectionStart, this.SelectionLength + this._addToSel); //this._addToSel = 0; }
/// <summary> /// This is called whenever a service control event happens such as pausing, stopping, etc... /// </summary> /// <param name="Opcode"></param> /// <param name="eventType"></param> /// <param name="eventData"></param> /// <param name="context"></param> /// <returns></returns> private int baseServiceControlHandler(ServicesAPI.ServiceControlType Opcode, int eventType, IntPtr eventData, IntPtr context) { System.Windows.Forms.Message m = new System.Windows.Forms.Message { Msg = DeviceNotification.WM_DEVICECHANGE, WParam = (IntPtr)eventType, LParam = eventData }; switch(Opcode) { case ServicesAPI.ServiceControlType.SERVICE_CONTROL_PAUSE: this.ServiceState = ServiceState.Paused; this._servStatus.dwCurrentState = ServicesAPI.ServiceCurrentStateType.SERVICE_PAUSED; try { this.ServiceSendCommand(Command.Pause); } catch(Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to pause the service:" + e); } ServicesAPI.SetServiceStatus(this._servStatusHandle, ref this._servStatus); break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_CONTINUE: this.ServiceState = ServiceState.Running; this._servStatus.dwCurrentState = ServicesAPI.ServiceCurrentStateType.SERVICE_RUNNING; ServicesAPI.SetServiceStatus(this._servStatusHandle, ref this._servStatus); try { this.ServiceSendCommand(Command.Continue); } catch(Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to continue the service:" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_STOP: this.ServiceState = ServiceState.Stopped; this._servStatus.dwWin32ExitCode = 0; this._servStatus.dwCurrentState = ServicesAPI.ServiceCurrentStateType.SERVICE_STOPPED; this._servStatus.dwCheckPoint = 0; this._servStatus.dwWaitHint = 0; ServicesAPI.SetServiceStatus(this._servStatusHandle, ref this._servStatus); try { this.ServiceSendCommand(Command.Stop); } catch(Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to stop the service:" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_SHUTDOWN: this.ServiceState = ServiceState.ShuttingDown; this._servStatus.dwCurrentState = ServicesAPI.ServiceCurrentStateType.SERVICE_STOPPED; ServicesAPI.SetServiceStatus(this._servStatusHandle, ref this._servStatus); try { this.ServiceSendCommand(Command.Shutdown); } catch(Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to shut down the service:" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_INTERROGATE: //this.ServiceState = ServiceState.Interrogating; //this.servStatus.dwCurrentState = ServicesAPI.ServiceCurrentStateType. .SERVICE_INTERROGATE; ServicesAPI.SetServiceStatus(this._servStatusHandle, ref this._servStatus); try { this.ServiceSendCommand(Command.Interrogate); } catch(Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to interrogate the service:" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_DEVICEEVENT: try { //TODO: Implement proper device event parsing!! var devevt = Notifications.Notifications.Transform(ref m); this.ServiceSendDeviceEvent(devevt.Device); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to update Device Event" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_HARDWAREPROFILECHANGE: try { this.ServiceSendHardwareProfileChange((ServicesAPI.SERVICE_CONTROL_HARDWAREPROFILECHANGE_Control)eventType); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to change hardware profile" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_NETBINDADD: try { this.ServiceSendNetBind(ServicesAPI.NetBindControl.NETBINDADD); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to netbind add" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_NETBINDDISABLE: try { this.ServiceSendNetBind(ServicesAPI.NetBindControl.NETBINDDISABLE); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to netbind disable" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_NETBINDENABLE : try { this.ServiceSendNetBind(ServicesAPI.NetBindControl.NETBINDENABLE); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to netbind enable" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_NETBINDREMOVE: try { this.ServiceSendNetBind(ServicesAPI.NetBindControl.NETBINDREMOVE); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to netbind remove" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_PARAMCHANGE: try { //TODO could be a mistake this.ServiceSendCustomCommand((int)eventData); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to send custom command" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_POWEREVENT: try { var powevt = Notifications.Notifications.Transform(ref m); this.ServiceSendPowerEvent(powevt.Power); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to process power event" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_PRESHUTDOWN: try { this.ServiceSendCommand(Command.PreShutdown); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to execute Pre Shutdown event" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_SESSIONCHANGE: try { var wtsnotification = (ServicesAPI.WTSSESSION_NOTIFICATION)Marshal.PtrToStructure(eventData,typeof(ServicesAPI.WTSSESSION_NOTIFICATION)); var sne = Notifications.SessionNotification.Transform( wtsnotification.dwSessionId); this.ServiceSendSessionChange((ServicesAPI.SERVICE_CONTROL_SESSIONCHANGE_Control)eventType,sne); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to process session change event" + e); } break; case ServicesAPI.ServiceControlType.SERVICE_CONTROL_TIMECHANGE: try { var sti = (ServicesAPI.SERVICE_TIMECHANGE_INFO)Marshal.PtrToStructure(eventData, typeof(ServicesAPI.SERVICE_TIMECHANGE_INFO)); this.ServiceSendTimeChange(sti.liOldTimeToDateTime(),sti.liNewTimeToDateTime()); } catch (Exception e) { this.Logger.WriteEntry(System.Diagnostics.EventLogEntryType.Error, "An exception occurred while trying to process time change event" + e); } break; //case ServicesAPI.ServiceControlType.SERVICE_CONTROL_TRIGGEREVENT: // break; } return 0; //NO_ERROR }
/// <summary>Processes a WM_INPUT message</summary> /// <param name="message">WM_INPUT message that will be processed</param> private void processWmInput(ref Message message) { // Retrieve the raw input data sent to the window int size = sizeOfRawInput; int result = UnsafeNativeMethods.GetRawInputData( message.LParam, UnsafeNativeMethods.RID_INPUT, out this.rawInput, ref size, sizeOfRawInputHeader ); if (result < 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // Only process data sent to the mouse if (this.rawInput.Header.Type == UnsafeNativeMethods.RIM_TYPEMOUSE) { bool isRelativeMouseMovement = (this.rawInput.Mouse.Flags & UnsafeNativeMethods.MOUSE_MOVE_RELATIVE) != 0; if (isRelativeMouseMovement) { int x = this.rawInput.Mouse.LastX; int y = this.rawInput.Mouse.LastY; OnMouseMoveHiDef(x, y); } else { int x = this.previousMouseX - this.rawInput.Mouse.LastX; int y = this.previousMouseY - this.rawInput.Mouse.LastY; this.previousMouseX = this.rawInput.Mouse.LastX; this.previousMouseY = this.rawInput.Mouse.LastY; OnMouseMoveHiDef(x, y); } } }
public UserAction() { this._eventcode = new System.Windows.Forms.Message(); this.threadid = 1; }
/// <summary> /// Overridden window message callback used to capture input for the window /// </summary> /// <param name="message">Window message sent to the window</param> protected override void WndProc(ref Message message) { base.WndProc(ref message); // Process the message differently based on its message id switch (message.Msg) { // Window is being asked which types of input it can process case (int)UnsafeNativeMethods.WindowMessages.WM_GETDLGCODE: { int returnCode = message.Result.ToInt32(); returnCode |= DlgCodeFlags; message.Result = new IntPtr(returnCode); break; } #if USE_WM_INPUT // Raw input data is being sent to the window case (int)UnsafeNativeMethods.WindowMessages.WM_INPUT: { processWmInput(ref message); break; } #endif // Key on the keyboard was pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_KEYDOWN: { int virtualKeyCode = message.WParam.ToInt32(); // bool repetition = (message.LParam.ToInt32() & WM_KEYDOWN_WASDOWN) != 0; OnKeyPressed((Keys)virtualKeyCode); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_KEYUP: { int virtualKeyCode = message.WParam.ToInt32(); OnKeyReleased((Keys)virtualKeyCode); break; } // Character has been entered on the keyboard case (int)UnsafeNativeMethods.WindowMessages.WM_CHAR: { char character = (char)message.WParam.ToInt32(); OnCharacterEntered(character); break; } // Mouse has been moved case (int)UnsafeNativeMethods.WindowMessages.WM_MOUSEMOVE: { if (!this.trackingMouse) { int result = UnsafeNativeMethods.TrackMouseEvent(ref this.mouseEventTrackData); Debug.Assert( result != 0, "Could not set up registration for mouse events", "The TrackMouseEvent() function failed, which means the game will not " + "detect when the mouse leaves the game window. This might result in " + "the assumed mouse position remaining somewhere near the window border " + "even though the mouse has been moved away from the game window." ); this.trackingMouse = (result != 0); } short x = (short)(message.LParam.ToInt32() & 0xFFFF); short y = (short)(message.LParam.ToInt32() >> 16); OnMouseMoved((float)x, (float)y); break; } // Left mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_LBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_LBUTTONDBLCLK: { OnMouseButtonPressed(MouseButtons.Left); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_LBUTTONUP: { OnMouseButtonReleased(MouseButtons.Left); break; } // Right mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_RBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_RBUTTONDBLCLK: { OnMouseButtonPressed(MouseButtons.Right); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_RBUTTONUP: { OnMouseButtonReleased(MouseButtons.Right); break; } // Middle mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_MBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_MBUTTONDBLCLK: { OnMouseButtonPressed(MouseButtons.Middle); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_MBUTTONUP: { OnMouseButtonReleased(MouseButtons.Middle); break; } // Extended mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_XBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_XBUTTONDBLCLK: { short button = (short)(message.WParam.ToInt32() >> 16); if (button == 1) OnMouseButtonPressed(MouseButtons.X1); if (button == 2) OnMouseButtonPressed(MouseButtons.X2); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_XBUTTONUP: { short button = (short)(message.WParam.ToInt32() >> 16); if (button == 1) OnMouseButtonReleased(MouseButtons.X1); if (button == 2) OnMouseButtonReleased(MouseButtons.X2); break; } // Mouse wheel rotated case (int)UnsafeNativeMethods.WindowMessages.WM_MOUSEHWHEEL: { short ticks = (short)(message.WParam.ToInt32() >> 16); OnMouseWheelRotated((float)ticks / 120.0f); break; } // Mouse has left the window's client area case (int)UnsafeNativeMethods.WindowMessages.WM_MOUSELEAVE: { OnMouseMoved(-1.0f, -1.0f); this.trackingMouse = false; break; } } }
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e) { // If we were just sitting next to a bolded parenthesis, we'll // carry the bold with us because the "SelectionChanged" event // does not appear to fire as we type. if (this.SelectionLength == 0 && this.SelectionFont != this.Font) this.SelectionFont = this.Font; if (e.KeyCode == System.Windows.Forms.Keys.C && e.Modifiers == (System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)) { #region CTRL-SHIFT-C this._parsing = true; try { this.CommentSelected(); this.Parse(); } finally { this._parsing = false; e.Handled = true; } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.U && e.Modifiers == (System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)) { #region CTRL-SHIFT-U this._parsing = true; try { this.UncommentSelected(); this.Parse(); } finally { this._parsing = false; e.Handled = true; } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Tab) { #region TAB Key this.EndAutoComplete(); if (e.Modifiers == System.Windows.Forms.Keys.Shift) { if (this.SelectionLength > 0) { // Unindent all selected lines. this._parsing = true; try { this.UnindentSelected(); this.Parse(); } //catch (Exception ex) //{ } finally { this._parsing = false; e.Handled = true; } } else { // Remove a single TAB char. int iLnSt = this.GetFirstCharIndexOfCurrentLine(); this._parsing = true; this.SuspendRefresh(); this.SuspendScroll(); try { if (this.SelectionStart > iLnSt && this.Text.Substring(this.SelectionStart - 1, 1) == "\t") { //int selStart = this.SelectionStart; //string text = string.Empty; //if (this.SelectionStart - 1 > 0) // text = this.Text.Substring(0, this.SelectionStart - 1); //text += this.Text.Substring(this.SelectionStart); //this.Parse(text); //this.SelectionStart = selStart - 1; // If we simulate a keypress rather then actually // alter the control's "Text" property, then we // don't have to parse the entire block of text // for color. System.Windows.Forms.Message msg = new System.Windows.Forms.Message(); msg.HWnd = new IntPtr(5572486); msg.Msg = (int)Win32Messages.WM_CHAR; msg.LParam = new IntPtr(917505); // We're passing a "Backspace" key instead of the tab. msg.WParam = new IntPtr(8); this.WndProc(ref msg); } } finally { this.ResumeRefresh(); this.ResumeScroll(); this._parsing = false; e.Handled = true; } } } else if (this.SelectionLength > 0) { // Indent all selected lines. this._parsing = true; try { this.IndexSelected(); this.DoParse(this.SelectionStart, this.SelectionLength); } //catch (Exception ex) //{ } finally { this._parsing = false; e.Handled = true; } } // If we fall out completely, it's just a standard TAB key-press, so // we don't need to do anything. #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Enter || e.KeyCode == System.Windows.Forms.Keys.Space) { #region ENTER / SPACE Key int iLn = this.GetLineFromCharIndex(this.SelectionStart); bool inAutoComplete = this._autoCompMenu != null && this._autoCompMenu.SelectedIndex > -1; try { // First thing we want to do is check to see if we were in the // middle of an "Auto Complete" operation. if (inAutoComplete) { // If the AutoComplete list is open and has an item selected, // we need to insert the selected text instead of // inserting the carriage return. this.SuspendRefresh(); this.SuspendScroll(); this._parsing = true; int selStart = this.SelectionStart, selLength = this.SelectionLength, dotIdx = this.Text.Substring(0, this.SelectionStart + this.SelectionLength).LastIndexOf('.'); if (this._autoCompMenu.Tag.ToString() == "Table") { string[] tblNm = this._autoCompMenu.Items[this._autoCompMenu.SelectedIndex].ToString().Split('.'); int qualSt = this.Text.Substring(0, dotIdx).LastIndexOf(' ') + 1; this.Select(qualSt, selStart + selLength - qualSt); if (tblNm[1].EndsWith("()")) { // Function string newText = string.Format("[{0}].{1}", tblNm[0], tblNm[1]); this.SelectedText = newText; this.Select(qualSt + newText.Length - 1, 0); } else if (tblNm[1].EndsWith(" SP")) // Stored Proceedure this.SelectedText = string.Format("EXEC [{0}].{1} ", tblNm[0], tblNm[1]); else // Table or View this.SelectedText = string.Format("[{0}].[{1}]", tblNm[0], tblNm[1]); } else { this.Select(dotIdx, selStart + selLength - dotIdx); this.SelectedText = string.Format(".[{0}]", this._autoCompMenu.Items[this._autoCompMenu.SelectedIndex].ToString()); } // We only want to suppress the key press if they pushed "ENTER", not "SPACE". if (e.KeyCode == System.Windows.Forms.Keys.Enter) { e.Handled = true; e.SuppressKeyPress = true; } } // We *always* want to terminate the autocomplete menu at this // point, if it's active. Either we just did an autocomplete // or the user made a keypress which bypassed the auto- // complete. Either way, we're done with it. this.EndAutoComplete(); //// If we weren't just doing an auto-complete, pressing space bar //// should start one, since we're not waiting for a '.' key //// press anymore. //if (!inAutoComplete) // this.ShowAutoComplete(this._autoCompleteTables.ToArray(), AutoCompleteType.Table); #region New Line - Tab-In moved to "KeyUp" event handler //if (!e.SuppressKeyPress) //{ // // When the user hits the return key, we want to keep the // // cursor "tabbed" in to match the previous line. // if (this.Lines.Length > 1) // { // string lnTxt = this.Lines[iLn]; // if (lnTxt.StartsWith("\t") || lnTxt.StartsWith(" ")) // { // // If the current line (we haven't actually processed the // // carriage-return yet) has any whitespace, we want to make // // the next line have the same leading whitespace. // string newTxt = ("\n" + lnTxt.Substring(0, lnTxt.Length - lnTxt.TrimStart('\t', ' ').Length)); // this.InsertText(newTxt, this.SelectionStart, false); // this.Select(this.SelectionStart + newTxt.Length, 0); // // Tell the base event that we processed this key manually and // // not to paste the 'newline' character // e.Handled = true; // } // } //} #endregion } finally { this._parsing = false; this.ResumeScroll(); this.ResumeRefresh(); } // When the user hits the enter key, we want to parse the line // we just left. Keep in mind that this method is called // before the NewLine character actually moves the cursor // to the next line. // We only need to do this parsing if the cursor was not at the // beginning of the line we were on. // LOGIC: If the cursor was at the beginning of the line, then either // no text was entered on that line, or we just moved any text // on the line down to the next line. if (e.KeyCode == System.Windows.Forms.Keys.Enter && !e.SuppressKeyPress) { int iSt = this.GetFirstCharIndexFromLine(iLn); if (this.SelectionStart != this.GetFirstCharIndexFromLine(iLn)) { //int iCnt = this.SelectionStart - iSt; //this.DoParse(iSt, iCnt); this.ParseCurrentLine(); } } #endregion } else if (e.KeyValue == 191) { #region SLASH Key // If the user closes a comment block /* */ we need to make sure we // haven't made anything after the closing block green already. if (this.SelectionStart > 0 && this.SelectionStart < this.Text.Length - 1 && this.Text.Substring(this.SelectionStart - 1, 1) == "*") { int endBlock = this.Text.IndexOf("/*", this.SelectionStart + 1) - 1; this.DoParse(this.SelectionStart + 1, ((endBlock > 0) ? endBlock : this.Text.Length) - (this.SelectionStart + 1), false); } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Delete) { #region DELETE Key //string cmpStr = this.Text.Substring(this.SelectionStart, 2); //if (this.SelectionStart < (this.Text.Length - 2) && (cmpStr == "/*" || cmpStr == "*/")) //{ // int endBlock = this.Text.IndexOf("/*", this.SelectionStart + 2); // this.DoParse(this.SelectionStart + 1, ((endBlock > 0) ? endBlock : this.Text.Length) - (this.SelectionStart + 1), false); //} // In case we just deleted a parenthesis, we need to "unbold" // any characters we might have stored a reference to. int iSelStart = this.SelectionStart, iSelLength = this.SelectionLength; this._parsing = true; try { for (int i = 0; i < this._bldChars.Count; i++) { this.Select(this._bldChars[i], 1); this.SelectionFont = this.Font; } this._bldChars.Clear(); } catch { } finally { if (this._selDir == AdvRichTextBox.SelectDirection.Backword) this.Select(iSelStart + iSelLength, -iSelLength); else this.Select(iSelStart, iSelLength); this._parsing = false; } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Back) { #region BACKSPACE Key //if (this.SelectionStart > 2) //{ // string cmpStr = this.Text.Substring(this.SelectionStart - 2, 2); // if (this.SelectionStart < (this.Text.Length - 2) && (cmpStr == "/*" || cmpStr == "*/")) // { // int endBlock = this.Text.IndexOf("/*", this.SelectionStart); // this.DoParse(this.SelectionStart, ((endBlock > 0) ? endBlock : this.Text.Length) - (this.SelectionStart), false); // } //} #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Up) { #region UP Key if (this._autoCompMenu != null && !this._autoCompMenu.IsDisposed) { e.Handled = true; if (this._autoCompMenu.SelectedIndex > 0) this._autoCompMenu.SelectedIndex--; } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Down) { #region DOWN Key if (this._autoCompMenu != null && !this._autoCompMenu.IsDisposed) { e.Handled = true; if (this._autoCompMenu.SelectedIndex < this._autoCompMenu.Items.Count - 1) this._autoCompMenu.SelectedIndex++; } #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Left) { #region LEFT Key if (this.SelectionStart <= this._autoCompStart || this.CurrentLine != this._autoCompLine) this.EndAutoComplete(); #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Right) { #region RIGHT Key if (this.CurrentLine != this._autoCompLine) this.EndAutoComplete(); #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.Home) { #region HOME Key this.EndAutoComplete(); // Move all this code to the AdvRichTextBox control class. //// If the user was holding the CTRL key when they pressed home, then //// we just move to the very beginning of the document. //if (e.Control) //{ // if (e.Shift) // //this.Select(0, this.SelectionStart + this.SelectionLength); // this.Select(this.SelectionStart, 0 - this.SelectionStart); // else // this.Select(0, 0); // e.Handled = true; //} //else //{ // // If the user presses the "HOME" key, then we want to move the // // cursor inteligently to either the beginning of the line, // // or the beginning of the actual text. // int curLn = this.GetLineFromCharIndex(this.SelectionStart), // curPos = this.SelectionStart, // lnStart = this.GetFirstCharIndexFromLine(curLn); // // If the current line doesn't begin with any whitespace, then we // // have nothing to do here. // string lnTxt = this.Lines[curLn]; // if (lnTxt.StartsWith("\t") || lnTxt.StartsWith(" ")) // { // int wsCharCnt = (lnTxt.Length - lnTxt.TrimStart('\t', ' ').Length), // selLen = lnStart - (curPos + SelectionLength); // if (this.SelectionStart == (lnStart + wsCharCnt)) // { // // If we're at the beginning of the text, then move to the // // first of the line. // if (e.Shift) // //this.Select(lnStart, (curPos + this.SelectionLength) - lnStart); // this.Select(curPos + this.SelectionLength, selLen); // else // this.Select(lnStart, 0); // } // else // { // // If the cursor is already at the beginning of the line, // // or anywhere else in the line, then move to the end // // of the whitespace. // if (e.Shift) // //this.Select(lnStart + wsCharCnt, (curPos - (lnStart + wsCharCnt)) + this.SelectionLength); // this.Select(curPos + this.SelectionLength, selLen + wsCharCnt); // else // this.Select(lnStart + wsCharCnt, 0); // } // e.Handled = true; // } //} #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.End) { #region END Key this.EndAutoComplete(); // Moved this code to the "AdvRichTextBox" control class. //if (e.Control) //{ // // If the users isn't holding the CTRL key, then it's just a // // standard End-of-Line keypress & we'll let the baes class // // deal with it. // if (e.Shift) // { // // User wants to select everything from here to the end of the document. // this.Select(this.SelectionStart, this.Text.Length - this.SelectionStart); // } // else // { // // Just move the cursor to the very end of the document. // this.Select(this.Text.Length, 0); // } // e.Handled = true; //} #endregion } else if (e.KeyValue == 56) { #region ASTRISK Key // The ASTRISK (*) will always close the AutoComplete menu, // since this effectively means "All Fields". this.EndAutoComplete(); #endregion } else if (e.KeyCode == System.Windows.Forms.Keys.F9) { this.Parse(); } else if (e.KeyData != System.Windows.Forms.Keys.Shift && this.IsInputKey(e.KeyData) && !e.Control && !e.Alt) { #region Any Other Input Character if (this._autoCompMenu != null) { if ((e.KeyValue >= 65 && e.KeyValue <= 90) || e.KeyValue == 189) { } else if (this._autoCompMenu.SelectedIndex > -1) { try { // If the AutoComplete list is open and has an item selected, // we need to insert the selected text followed by a // single space character. this.SuspendRefresh(); this._parsing = true; int selStart = this.SelectionStart, selLength = this.SelectionLength, dotIdx = this.Text.Substring(0, this.SelectionStart + this.SelectionLength).LastIndexOf('.'); //System.Windows.Forms.KeysConverter kc = new System.Windows.Forms.KeysConverter(); this.Select(dotIdx, selStart + selLength - dotIdx); this.SelectedText = string.Format(".[{0}]", this._autoCompMenu.Items[this._autoCompMenu.SelectedIndex].ToString()); this.EndAutoComplete(); } finally { this._parsing = false; this.ResumeRefresh(); } } } #endregion } if (e.Handled) e.SuppressKeyPress = true; this._lastKeyPress = e.KeyData; base.OnKeyDown(e); }
/// <summary>Filters out a message before it is dispatched</summary> /// <param name="message"> /// Message that will be dispatched. You must not modify this message. /// </param> /// <returns> /// True if the message has been processed by the filter and should not be /// dispatched or false to continue processing of the message. /// </returns> bool IMessageFilter.PreFilterMessage(ref Message message) { // Process the message differently based on its message id switch (message.Msg) { case (int)UnsafeNativeMethods.WindowMessages.WM_SYSKEYDOWN: { int virtualKeyCode = message.WParam.ToInt32(); // Don't handle these Alt+key presses because they'd block Windows' shortcuts bool dontHandle = (virtualKeyCode == (int)Keys.F4) || (virtualKeyCode == (int)Keys.Escape) || (virtualKeyCode == (int)Keys.Space); if(dontHandle) { break; } goto case (int)UnsafeNativeMethods.WindowMessages.WM_KEYDOWN; } // Key on the keyboard was pressed case (int)UnsafeNativeMethods.WindowMessages.WM_KEYDOWN: { int virtualKeyCode = message.WParam.ToInt32(); switch (virtualKeyCode) { #if false // XNA doesn't want to distinguish Return and Enter case 0x0D: { // VK_ENTER bool extended = (message.LParam.ToInt32() & 0x01000000) != 0; if (extended) { OnKeyPressed(Keys.Enter); } else { OnKeyPressed(Keys.??); } break; } #endif case 0x10: { // VK_SHIFT OnKeyPressed( (Keys)UnsafeNativeMethods.MapVirtualKey( (uint)(message.LParam.ToInt32() & 0x00FF0000) >> 16, (uint)UnsafeNativeMethods.MapType.ScanCodeToVirtualKeyEx ) ); break; } case 0x11: { // VK_CONTROL bool extended = (message.LParam.ToInt32() & 0x01000000) != 0; if (extended) { OnKeyPressed(Keys.RightControl); } else { OnKeyPressed(Keys.LeftControl); } break; } case 0x12: { // VK_MENU bool extended = (message.LParam.ToInt32() & 0x01000000) != 0; if (extended) { OnKeyPressed(Keys.RightAlt); } else { OnKeyPressed(Keys.LeftAlt); } break; } default: { OnKeyPressed((Keys)virtualKeyCode); break; } } UnsafeNativeMethods.TranslateMessage(ref message); return true; // consumed! } // Key on the keyboard was released case (int)UnsafeNativeMethods.WindowMessages.WM_SYSKEYUP: case (int)UnsafeNativeMethods.WindowMessages.WM_KEYUP: { int virtualKeyCode = message.WParam.ToInt32(); switch (virtualKeyCode) { #if false // We could, but XNA doesn't want to distinguish Return and Enter case 0x0D: { // VK_ENTER bool extended = (message.LParam.ToInt32() & 0x01000000) != 0; if (extended) { OnKeyReleased(Keys.Enter); } else { OnKeyReleased(Keys.??); } break; } #endif case 0x10: { // VK_SHIFT OnKeyReleased( (Keys)UnsafeNativeMethods.MapVirtualKey( (uint)(message.LParam.ToInt32() & 0x00FF0000) >> 16, (uint)UnsafeNativeMethods.MapType.ScanCodeToVirtualKeyEx ) ); break; } case 0x11: { // VK_CONTROL bool isExtendedKey = (message.LParam.ToInt32() & (1 << 24)) != 0; if (isExtendedKey) { OnKeyReleased(Keys.RightControl); } else { OnKeyReleased(Keys.LeftControl); } break; } case 0x12: { // VK_MENU bool isExtendedKey = (message.LParam.ToInt32() & (1 << 24)) != 0; if (isExtendedKey) { OnKeyReleased(Keys.RightAlt); } else { OnKeyReleased(Keys.LeftAlt); } break; } default: { OnKeyReleased((Keys)virtualKeyCode); break; } } return true; // consumed! } // Character has been entered on the keyboard case (int)UnsafeNativeMethods.WindowMessages.WM_CHAR: { char character = (char)message.WParam.ToInt32(); OnCharacterEntered(character); return true; // consumed! } // Mouse has been moved case (int)UnsafeNativeMethods.WindowMessages.WM_MOUSEMOVE: { if (!this.trackingMouse) { int result = UnsafeNativeMethods.TrackMouseEvent(ref this.mouseEventTrackData); Debug.Assert( result != 0, "Could not set up registration for mouse events", "The TrackMouseEvent() function failed, which means the game will not " + "detect when the mouse leaves the game window. This might result in " + "the assumed mouse position remaining somewhere near the window border " + "even though the mouse has been moved away from the game window." ); this.trackingMouse = (result != 0); } short x = (short)(message.LParam.ToInt32() & 0xFFFF); short y = (short)(message.LParam.ToInt32() >> 16); OnMouseMoved((float)x, (float)y); break; } // Left mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_LBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_LBUTTONDBLCLK: { OnMouseButtonPressed(MouseButtons.Left); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_LBUTTONUP: { OnMouseButtonReleased(MouseButtons.Left); break; } // Right mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_RBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_RBUTTONDBLCLK: { OnMouseButtonPressed(MouseButtons.Right); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_RBUTTONUP: { OnMouseButtonReleased(MouseButtons.Right); break; } // Middle mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_MBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_MBUTTONDBLCLK: { OnMouseButtonPressed(MouseButtons.Middle); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_MBUTTONUP: { OnMouseButtonReleased(MouseButtons.Middle); break; } // Extended mouse button pressed / released case (int)UnsafeNativeMethods.WindowMessages.WM_XBUTTONDOWN: case (int)UnsafeNativeMethods.WindowMessages.WM_XBUTTONDBLCLK: { short button = (short)(message.WParam.ToInt32() >> 16); if (button == 1) OnMouseButtonPressed(MouseButtons.X1); if (button == 2) OnMouseButtonPressed(MouseButtons.X2); break; } case (int)UnsafeNativeMethods.WindowMessages.WM_XBUTTONUP: { short button = (short)(message.WParam.ToInt32() >> 16); if (button == 1) OnMouseButtonReleased(MouseButtons.X1); if (button == 2) OnMouseButtonReleased(MouseButtons.X2); break; } // Mouse wheel rotated case (int)UnsafeNativeMethods.WindowMessages.WM_MOUSEHWHEEL: { short ticks = (short)(message.WParam.ToInt32() >> 16); OnMouseWheelRotated((float)ticks / 120.0f); break; } // Mouse has left the window's client area case (int)UnsafeNativeMethods.WindowMessages.WM_MOUSELEAVE: { OnMouseMoved(-1.0f, -1.0f); this.trackingMouse = false; break; } } return false; }
/// <summary> /// Callback функция для хука -- прослушивание событий мыши. /// </summary> private int MouseCallbackFunctionListener(int code, IntPtr wParam, IntPtr lparam) { MSLLHOOKSTRUCT mouseInfo = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lparam, typeof(MSLLHOOKSTRUCT)); // Инициализируем новый итем ActionLogger.UserAction uaMouse = new ActionLogger.UserAction(); System.Windows.Forms.Message msg = new System.Windows.Forms.Message(); msg.Msg = wParam.ToInt32(); if (msg.Msg == WM_LBUTTONDOWN || msg.Msg == WM_LBUTTONUP) { //Записываем координаты мыши в DWORD uint MousePt = unchecked( (uint)((uint)mouseInfo.pt.Y << 16) | (uint)mouseInfo.pt.X); System.Drawing.Point pt = new System.Drawing.Point(mouseInfo.pt.X, mouseInfo.pt.Y); //Рекурсивно находим самое нижнее из всех дочерних окон, в котором находится наша точка IntPtr OldWnd = weFinder.ParentHandle; IntPtr OldCWnd = IntPtr.Zero; IntPtr hwnd = weFinder.FindWindowAtPos(pt); while (hwnd != IntPtr.Zero) { OldCWnd = hwnd; weFinder.ParentHandle = hwnd; hwnd = weFinder.FindWindowAtPos(pt); } weFinder.ParentHandle = OldWnd; hwnd = OldCWnd; if (hwnd != IntPtr.Zero) { //Получаем текст окна int len = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, new StringBuilder()).ToInt32()+1; StringBuilder strWindowText = new StringBuilder(len); SendMessage(hwnd, WM_GETTEXT, len , strWindowText); uaMouse.BriefInfo = strWindowText.ToString() + ":"; // Получаем класс окна StringBuilder strWindowClass = new StringBuilder(128); WindowsEnumerator.GetClassName(hwnd,strWindowClass,128); uaMouse.BriefInfo += strWindowClass.ToString(); //Формирует ординарное сообщение Windows для помещения в хранилище IntPtr PtrToPt = new IntPtr(MousePt); msg.LParam = PtrToPt; msg.WParam = new IntPtr(1); uaMouse.KeyCode = (mouseInfo.mouseData >> 16); uaMouse.EventCode = msg; uaMouse.ThreadId = this.ThreadId; //Записываем новый итем в модель. ActionHost.AddItem(uaMouse); } } // Передаем управление следующему хуку, если такой есть в системе. return CallNextHookEx(IntPtr.Zero, code, wParam, lparam); }
/// <summary> /// Каллбэк функция для клавиатурных событий. Пока отключена /// </summary> /// <param name="code">Флаг передачи управления следующему хуку</param> /// <param name="wParam"> Содержит доп. информацию о сообщении </param> /// <param name="lparam"> Содержит информацию о нажатых клавишах</param> /// <returns></returns> private int KBCallbackFunction(int code, IntPtr wParam, IntPtr lparam) { /*MSG msgstruct = (MSG) Marshal.PtrToStructure(wParam, typeof(MSG)); System.Windows.Forms.Message Message_ = new System.Windows.Forms.Message(); Message_.HWnd = msgstruct.hwnd; Message_.LParam = msgstruct.lParam;*/ /*Message_.WParam = msgstruct.wParam;*/ ActionLogger.UserAction uaKbd = new ActionLogger.UserAction(); KBDLLHOOKSTRUCT kbinfo = (KBDLLHOOKSTRUCT) Marshal.PtrToStructure(lparam,typeof(KBDLLHOOKSTRUCT)); uaKbd.ThreadId = this.ThreadId; System.Windows.Forms.Message msg = new System.Windows.Forms.Message(); msg.Msg = wParam.ToInt32(); msg.HWnd = IntPtr.Zero; msg.WParam = wParam; msg.LParam = lparam; uaKbd.EventCode = msg; uaKbd.ControlHandle = IntPtr.Zero; uaKbd.KeyCode= (int)kbinfo.vkCode; ActionHost.AddItem(uaKbd); /* BinaryFormatter bfSerializer = new BinaryFormatter(); NamedPipeServerStream pipeStream = new NamedPipeServerStream("hookpipe"); bfSerializer.Serialize(pipeStream,uaKbd); pipeStream.Close();*/ return CallNextHookEx(IntPtr.Zero, code, wParam, lparam); }
public UserAction(System.Windows.Forms.Message message, uint threadId) { this._eventcode = message; this.threadid = threadId; }
private void HandleInitializeItems(Message m) { InitializeItems(); }
/// <summary> /// Callback функция для хука -- определение окна под мышью. /// </summary> private int MouseCallBackFunctionFinder(int code, IntPtr wparam, IntPtr LParam) { MSLLHOOKSTRUCT mouseInfo = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(LParam, typeof(MSLLHOOKSTRUCT)); System.Windows.Forms.Message msg = new System.Windows.Forms.Message(); msg.Msg = wparam.ToInt32(); if (msg.Msg == WM_LBUTTONDOWN) { //Записываем координаты мыши в DWORD uint MousePt = unchecked((uint)((uint)mouseInfo.pt.Y << 16) | (uint)mouseInfo.pt.X); System.Drawing.Point pt = new System.Drawing.Point(mouseInfo.pt.X, mouseInfo.pt.Y); // Находим ближайшее окно IntPtr hwnd = weFinder.FindWindowAtPos(pt); ActionHost.TargetWindow = hwnd; RECT rctWindowRect = new RECT(); GetWindowRect(hwnd, out rctWindowRect); ActionHost.ptWindowPoint = new Point(rctWindowRect._Left, rctWindowRect._Top); ActionHost.szTargetBounds.Width = rctWindowRect._Right - rctWindowRect._Left; ActionHost.szTargetBounds.Height = rctWindowRect._Bottom - rctWindowRect._Top; } return CallNextHookEx(IntPtr.Zero, code, wparam, LParam); }
private void HandleInitializeTab(Message m) { int exStyle = UnsafeNativeMethods.GetWindowLong(UnsafeNativeMethods.GetParent(Handle), UnsafeNativeMethods.GWL_EXSTYLE); if ((exStyle | UnsafeNativeMethods.WS_EX_CONTROLPARENT) != UnsafeNativeMethods.WS_EX_CONTROLPARENT) { exStyle ^= UnsafeNativeMethods.WS_EX_CONTROLPARENT; UnsafeNativeMethods.SetWindowLong(UnsafeNativeMethods.GetParent(Handle), UnsafeNativeMethods.GWL_EXSTYLE, exStyle); } Invalidate(true); }
protected override bool GetHitTest(System.Drawing.Point point) { if (this.SelectionService.PrimarySelection == this.Control) { TCHITTESTINFO hti = new TCHITTESTINFO(); hti.pt = this.Control.PointToClient(point); hti.flags = 0; System.Windows.Forms.Message m = new System.Windows.Forms.Message(); m.HWnd = this.Control.Handle; m.Msg = TCM_HITTEST; IntPtr lparam = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(hti)); System.Runtime.InteropServices.Marshal.StructureToPtr(hti, lparam, false); m.LParam = lparam; base.WndProc(ref m); System.Runtime.InteropServices.Marshal.FreeHGlobal (lparam); if (m.Result.ToInt32() != -1) return hti.flags != TabControlHitTest.TCHT_NOWHERE; } return false; }