private void Button_MouseLeave(object sender, MouseEventArgs args) { if (clicking) { if (pressed) { pressed = false; Invalidate(); } } }
private void Button_MouseEnter(object sender, MouseEventArgs args) { if (clicking) { if (!pressed) { pressed = true; Invalidate(); } } }
/// <summary> /// Обработчик отвечает за вывод на передний план неактивных окон, на которые нажали мышкой, /// и за обработку мыши, когда имеется модальное окно - в этом случае обработчик не пропускает /// события, которые идут мимо модального окна, дальше по дереву (Tunneling) - устанавливая /// Handled в True, либо закрывает модальное окно, если оно было показано с флагом /// OutsideClickClosesWindow. /// eventType = 0 - PreviewMouseDown /// eventType = 1 - PreviewMouseUp /// eventType = 2 - PreviewMouseMove /// </summary> private void onPreviewMouseEvents(MouseEventArgs args, int eventType) { bool handle = false; check: if ( isTopWindowModal( ) ) { Window modalWindow = ( Window ) Children[ Children.Count - 1 ]; Window windowClicked = VisualTreeHelper.FindClosestParent<Window>((Control)args.Source); if ( windowClicked != modalWindow ) { if ( windowInfos[ modalWindow ].OutsideClickClosesWindow && (eventType == 0 || eventType == 2 && args.LeftButton == MouseButtonState.Pressed) ) { // закрываем текущее модальное окно CloseWindow( modalWindow ); // далее обрабатываем событие как обычно handle = true; // Если дальше снова модальное окно, проверку нужно повторить, и закрыть // его тоже, и так далее. Можно отрефакторить как вызов подпрограммы // вида while (closeTopModalWindowIfNeed()) ; goto check; } else { // прекращаем распространение события (правда, контролы, подписавшиеся с флагом // handledEventsToo, получат его в любом случае) и генерацию соответствующего // парного не-preview события args.Handled = true; } } } else { handle = true; } if (handle && (eventType == 0 || eventType == 2 && args.LeftButton == MouseButtonState.Pressed)) { Window windowClicked = VisualTreeHelper.FindClosestParent< Window >( ( Control ) args.Source ); if ( null != windowClicked ) { activateWindow( windowClicked ); } else { Menu menu = VisualTreeHelper.FindClosestParent< Menu >( ( Control ) args.Source ); if ( null != menu ) { activateMenu( ); } } } }
private void onPreviewMouseUp(object sender, MouseEventArgs args) { onPreviewMouseEvents(args, 1); }
private void onPreviewMouseDown(object sender, MouseEventArgs args) { onPreviewMouseEvents(args, 0); }
private void onPreviewMouseMove(object sender, MouseEventArgs args) { onPreviewMouseEvents(args, 2); }
private bool processRoutedEvent(RoutedEvent routedEvent, RoutedEventArgs args) { // List<RoutedEventTargetInfo> subscribedTargets = getTargetsSubscribedTo(routedEvent); Control capturingControl = inputCaptureStack.Count != 0 ? inputCaptureStack.Peek() : null; // if (routedEvent.RoutingStrategy == RoutingStrategy.Direct) { if (null == subscribedTargets) return false; // RoutedEventTargetInfo targetInfo = subscribedTargets.FirstOrDefault(info => info.target == args.Source); if (null == targetInfo) return false; // если имеется контрол, захватывающий события, события получает только он сам // и его дочерние контролы if ( capturingControl != null ) { if ( !(args.Source is Control) ) return false; if ( !isControlAllowedToReceiveEvents( ( Control ) args.Source, capturingControl ) ) return false; } // copy handlersList to local list to avoid modifications when enumerating foreach (DelegateInfo delegateInfo in new List< DelegateInfo >(targetInfo.handlersList)) { if (!args.Handled || delegateInfo.handledEventsToo) { if (delegateInfo.@delegate is RoutedEventHandler) { ((RoutedEventHandler) delegateInfo.@delegate).Invoke(targetInfo.target, args); } else { [email protected](targetInfo.target, args); } } } } Control source = (Control) args.Source; // path to source from root element down to Source List<Control> path = new List<Control>(); Control current = source; while (null != current) { // та же логика с контролом, захватившим обработку сообщений // если имеется контрол, захватывающий события, события получает только он сам // и его дочерние контролы if ( capturingControl == null || isControlAllowedToReceiveEvents( current, capturingControl ) ) { path.Insert( 0, current ); current = current.Parent; } else { break; } } if (routedEvent.RoutingStrategy == RoutingStrategy.Tunnel) { if (subscribedTargets != null) { foreach (Control potentialTarget in path) { Control target = potentialTarget; RoutedEventTargetInfo targetInfo = subscribedTargets.FirstOrDefault(info => info.target == target); if (null != targetInfo) { foreach (DelegateInfo delegateInfo in new List< DelegateInfo >(targetInfo.handlersList)) { if (!args.Handled || delegateInfo.handledEventsToo) { if (delegateInfo.@delegate is RoutedEventHandler) { ((RoutedEventHandler) delegateInfo.@delegate).Invoke(target, args); } else { [email protected](target, args); } } } } } } // для парных Preview-событий запускаем соответствующие настоящие события, // сохраняя при этом Handled (если Preview событие помечено как Handled=true, // то и настоящее событие будет маршрутизировано с Handled=true) if (routedEvent == Control.PreviewMouseDownEvent) { MouseButtonEventArgs mouseArgs = ( ( MouseButtonEventArgs ) args ); MouseButtonEventArgs argsNew = new MouseButtonEventArgs( args.Source, Control.MouseDownEvent, mouseArgs.RawPosition, mouseArgs.LeftButton, mouseArgs.MiddleButton, mouseArgs.RightButton, mouseArgs.ChangedButton ); argsNew.Handled = args.Handled; eventsQueue.Enqueue(argsNew); } if (routedEvent == Control.PreviewMouseUpEvent) { MouseButtonEventArgs mouseArgs = ( ( MouseButtonEventArgs ) args ); MouseButtonEventArgs argsNew = new MouseButtonEventArgs( args.Source, Control.MouseUpEvent, mouseArgs.RawPosition, mouseArgs.LeftButton, mouseArgs.MiddleButton, mouseArgs.RightButton, mouseArgs.ChangedButton ); argsNew.Handled = args.Handled; eventsQueue.Enqueue(argsNew); } if (routedEvent == Control.PreviewMouseMoveEvent) { MouseEventArgs mouseArgs = ( ( MouseEventArgs ) args ); MouseEventArgs argsNew = new MouseEventArgs( args.Source, Control.MouseMoveEvent, mouseArgs.RawPosition, mouseArgs.LeftButton, mouseArgs.MiddleButton, mouseArgs.RightButton ); argsNew.Handled = args.Handled; eventsQueue.Enqueue(argsNew); } if ( routedEvent == Control.PreviewMouseWheelEvent ) { MouseWheelEventArgs oldArgs = ((MouseWheelEventArgs)args); MouseEventArgs argsNew = new MouseWheelEventArgs( args.Source, Control.MouseWheelEvent, oldArgs.RawPosition, oldArgs.LeftButton, oldArgs.MiddleButton, oldArgs.RightButton, oldArgs.Delta ); argsNew.Handled = args.Handled; eventsQueue.Enqueue(argsNew); } if (routedEvent == Control.PreviewKeyDownEvent) { KeyEventArgs argsNew = new KeyEventArgs(args.Source, Control.KeyDownEvent); KeyEventArgs keyEventArgs = ( ( KeyEventArgs ) args ); argsNew.UnicodeChar = keyEventArgs.UnicodeChar; argsNew.bKeyDown = keyEventArgs.bKeyDown; argsNew.dwControlKeyState = keyEventArgs.dwControlKeyState; argsNew.wRepeatCount = keyEventArgs.wRepeatCount; argsNew.wVirtualKeyCode = keyEventArgs.wVirtualKeyCode; argsNew.wVirtualScanCode = keyEventArgs.wVirtualScanCode; argsNew.Handled = args.Handled; eventsQueue.Enqueue(argsNew); } if (routedEvent == Control.PreviewKeyUpEvent) { KeyEventArgs argsNew = new KeyEventArgs(args.Source, Control.KeyUpEvent); KeyEventArgs keyEventArgs = ( ( KeyEventArgs ) args ); argsNew.UnicodeChar = keyEventArgs.UnicodeChar; argsNew.bKeyDown = keyEventArgs.bKeyDown; argsNew.dwControlKeyState = keyEventArgs.dwControlKeyState; argsNew.wRepeatCount = keyEventArgs.wRepeatCount; argsNew.wVirtualKeyCode = keyEventArgs.wVirtualKeyCode; argsNew.wVirtualScanCode = keyEventArgs.wVirtualScanCode; argsNew.Handled = args.Handled; eventsQueue.Enqueue(argsNew); } } if (routedEvent.RoutingStrategy == RoutingStrategy.Bubble) { if (subscribedTargets != null) { for (int i = path.Count - 1; i >= 0; i--) { Control target = path[i]; RoutedEventTargetInfo targetInfo = subscribedTargets.FirstOrDefault(info => info.target == target); if (null != targetInfo) { // foreach (DelegateInfo delegateInfo in new List< DelegateInfo >(targetInfo.handlersList)) { if (!args.Handled || delegateInfo.handledEventsToo) { if (delegateInfo.@delegate is RoutedEventHandler) { ((RoutedEventHandler) delegateInfo.@delegate).Invoke(target, args); } else { [email protected](target, args); } } } } } } } return args.Handled; }
public void ParseInputEvent(INPUT_RECORD inputRecord, Control rootElement) { if (inputRecord.EventType == EventType.MOUSE_EVENT) { MOUSE_EVENT_RECORD mouseEvent = inputRecord.MouseEvent; if (mouseEvent.dwEventFlags != MouseEventFlags.PRESSED_OR_RELEASED && mouseEvent.dwEventFlags != MouseEventFlags.MOUSE_MOVED && mouseEvent.dwEventFlags != MouseEventFlags.DOUBLE_CLICK && mouseEvent.dwEventFlags != MouseEventFlags.MOUSE_WHEELED && mouseEvent.dwEventFlags != MouseEventFlags.MOUSE_HWHEELED) { // throw new InvalidOperationException("Flags combination in mouse event was not expected."); } Point rawPosition; if (mouseEvent.dwEventFlags == MouseEventFlags.MOUSE_MOVED || mouseEvent.dwEventFlags == MouseEventFlags.PRESSED_OR_RELEASED) { rawPosition = new Point(mouseEvent.dwMousePosition.X, mouseEvent.dwMousePosition.Y); lastMousePosition = rawPosition; } else { // При событии MOUSE_WHEELED в Windows некорректно устанавливается mouseEvent.dwMousePosition // Поэтому для определения элемента, над которым производится прокручивание колёсика, мы // вынуждены сохранять координаты, полученные при предыдущем событии мыши rawPosition = lastMousePosition; } Control topMost = findSource(rawPosition, rootElement); // если мышь захвачена контролом, то события перемещения мыши доставляются только ему, // события, связанные с нажатием мыши - тоже доставляются только ему, вместо того // контрола, над которым событие было зарегистрировано. Такой механизм необходим, // например, для корректной обработки перемещений окон (вверх или в стороны) Control source = (inputCaptureStack.Count != 0) ? inputCaptureStack.Peek() : topMost; if (mouseEvent.dwEventFlags == MouseEventFlags.MOUSE_MOVED) { MouseButtonState leftMouseButtonState = getLeftButtonState(mouseEvent.dwButtonState); MouseButtonState middleMouseButtonState = getMiddleButtonState(mouseEvent.dwButtonState); MouseButtonState rightMouseButtonState = getRightButtonState(mouseEvent.dwButtonState); // MouseEventArgs mouseEventArgs = new MouseEventArgs(source, Control.PreviewMouseMoveEvent, rawPosition, leftMouseButtonState, middleMouseButtonState, rightMouseButtonState ); eventsQueue.Enqueue(mouseEventArgs); // lastLeftMouseButtonState = leftMouseButtonState; lastMiddleMouseButtonState = middleMouseButtonState; lastRightMouseButtonState = rightMouseButtonState; // detect mouse enter / mouse leave events // path to source from root element down List<Control> mouseOverStack = new List<Control>(); Control current = topMost; while (null != current) { mouseOverStack.Insert(0, current); current = current.Parent; } int index; for (index = 0; index < Math.Min(mouseOverStack.Count, prevMouseOverStack.Count); index++) { if (mouseOverStack[index] != prevMouseOverStack[index]) break; } for (int i = prevMouseOverStack.Count - 1; i >= index; i-- ) { Control control = prevMouseOverStack[i]; MouseEventArgs args = new MouseEventArgs(control, Control.MouseLeaveEvent, rawPosition, leftMouseButtonState, middleMouseButtonState, rightMouseButtonState ); eventsQueue.Enqueue(args); } for (int i = index; i < mouseOverStack.Count; i++ ) { // enqueue MouseEnter event Control control = mouseOverStack[i]; MouseEventArgs args = new MouseEventArgs(control, Control.MouseEnterEvent, rawPosition, leftMouseButtonState, middleMouseButtonState, rightMouseButtonState ); eventsQueue.Enqueue(args); } prevMouseOverStack.Clear(); prevMouseOverStack.AddRange(mouseOverStack); } if (mouseEvent.dwEventFlags == MouseEventFlags.PRESSED_OR_RELEASED) { // MouseButtonState leftMouseButtonState = getLeftButtonState(mouseEvent.dwButtonState); MouseButtonState middleMouseButtonState = getMiddleButtonState(mouseEvent.dwButtonState); MouseButtonState rightMouseButtonState = getRightButtonState(mouseEvent.dwButtonState); // if (leftMouseButtonState != lastLeftMouseButtonState) { MouseButtonEventArgs eventArgs = new MouseButtonEventArgs(source, leftMouseButtonState == MouseButtonState.Pressed ? Control.PreviewMouseDownEvent : Control.PreviewMouseUpEvent, rawPosition, leftMouseButtonState, lastMiddleMouseButtonState, lastRightMouseButtonState, MouseButton.Left ); eventsQueue.Enqueue(eventArgs); } if (middleMouseButtonState != lastMiddleMouseButtonState) { MouseButtonEventArgs eventArgs = new MouseButtonEventArgs(source, middleMouseButtonState == MouseButtonState.Pressed ? Control.PreviewMouseDownEvent : Control.PreviewMouseUpEvent, rawPosition, lastLeftMouseButtonState, middleMouseButtonState, lastRightMouseButtonState, MouseButton.Middle ); eventsQueue.Enqueue(eventArgs); } if (rightMouseButtonState != lastRightMouseButtonState) { MouseButtonEventArgs eventArgs = new MouseButtonEventArgs(source, rightMouseButtonState == MouseButtonState.Pressed ? Control.PreviewMouseDownEvent : Control.PreviewMouseUpEvent, rawPosition, lastLeftMouseButtonState, lastMiddleMouseButtonState, rightMouseButtonState, MouseButton.Right ); eventsQueue.Enqueue(eventArgs); } // lastLeftMouseButtonState = leftMouseButtonState; lastMiddleMouseButtonState = middleMouseButtonState; lastRightMouseButtonState = rightMouseButtonState; } if (mouseEvent.dwEventFlags == MouseEventFlags.MOUSE_WHEELED) { MouseWheelEventArgs args = new MouseWheelEventArgs( topMost, Control.PreviewMouseWheelEvent, rawPosition, lastLeftMouseButtonState, lastMiddleMouseButtonState, lastRightMouseButtonState, mouseEvent.dwButtonState > 0 ? 1 : -1 ); eventsQueue.Enqueue( args ); } } if (inputRecord.EventType == EventType.KEY_EVENT) { KEY_EVENT_RECORD keyEvent = inputRecord.KeyEvent; KeyEventArgs eventArgs = new KeyEventArgs( ConsoleApplication.Instance.FocusManager.FocusedElement, keyEvent.bKeyDown ? Control.PreviewKeyDownEvent : Control.PreviewKeyUpEvent); eventArgs.UnicodeChar = keyEvent.UnicodeChar; eventArgs.bKeyDown = keyEvent.bKeyDown; eventArgs.dwControlKeyState = keyEvent.dwControlKeyState; eventArgs.wRepeatCount = keyEvent.wRepeatCount; eventArgs.wVirtualKeyCode = keyEvent.wVirtualKeyCode; eventArgs.wVirtualScanCode = keyEvent.wVirtualScanCode; eventsQueue.Enqueue(eventArgs); } }
private void onPreviewMouseDown( object sender, MouseEventArgs e ) { PassFocusToChildUnderPoint( e ); }
private void onPreviewMouseMove( object sender, MouseEventArgs args ) { if ( args.LeftButton == MouseButtonState.Pressed ) { onPreviewMouseDown( sender, args ); } }
private void onPanelMouseMove( object sender, MouseEventArgs e ) { if ( e.LeftButton == MouseButtonState.Pressed ) { PassFocusToChildUnderPoint( e ); } }
private void onMouseDown( object sender, MouseEventArgs args ) { if (!disabled) openMenu( ); args.Handled = true; }
private void onMouseMove( object sender, MouseEventArgs args ) { // Mouse move opens the submenus only in root level if ( !disabled && args.LeftButton == MouseButtonState.Pressed /*&& Parent.Parent is Menu*/ ) { openMenu( ); } args.Handled = true; }
private void onMouseUp( object sender, MouseEventArgs args ) { if ( Type == MenuItemType.Item ) { RaiseClick( ); args.Handled = true; } }
public void Window_OnMouseMove(object sender, MouseEventArgs args) { if (closing) { Point point = args.GetPosition(this); bool anyChanged = false; if (point.x == 3 && point.y == 0) { if (!showClosingGlyph) { showClosingGlyph = true; anyChanged = true; } } else { if (showClosingGlyph) { showClosingGlyph = false; anyChanged = true; } } if (anyChanged) Invalidate(); args.Handled = true; } if (moving) { Point parentPoint = args.GetPosition(getWindowsHost()); Vector vector = new Vector(parentPoint.X - movingStartPoint.x, parentPoint.Y - movingStartPoint.y); X = movingStartX + vector.X; Y = movingStartY + vector.Y; getWindowsHost().Invalidate(); args.Handled = true; } if (resizing) { Point parentPoint = args.GetPosition(getWindowsHost()); int deltaWidth = parentPoint.X - resizingStartPoint.x; int deltaHeight = parentPoint.Y - resizingStartPoint.y; int width = resizingStartWidth + deltaWidth; int height = resizingStartHeight + deltaHeight; bool anyChanged = false; if (width >= 4) { this.Width = width; anyChanged = true; } if (height >= 3) { this.Height = height; anyChanged = true; } if (anyChanged) Invalidate(); args.Handled = true; } }
private void OnMouseMove( object sender, MouseEventArgs args ) { if ( args.LeftButton == MouseButtonState.Pressed ) { int index = args.GetPosition( this ).Y; if ( !disabledItemsIndexes.Contains(index) && SelectedItemIndex != index ) { SelectedItemIndex = index; Invalidate( ); } } args.Handled = true; }