【问题标题】:how to GetMousePosition anywhere on the screen, outside the bounds of window (or any Visual)如何 GetMousePosition 在屏幕上的任何位置,在窗口(或任何视觉)边界之外
【发布时间】:2010-11-26 18:12:04
【问题描述】:

我想在屏幕上的任意位置跟踪鼠标光标的位置,在屏幕坐标中。那么即使鼠标光标移动到了窗口边界之外,有没有办法获取鼠标光标的位置呢?

我正在做的是试图让一个弹出窗口跟随鼠标光标,即使它移出主窗口。

这是我尝试过(但没有奏效)的代码 sn-p:

        private void OnLoaded(object sender, RoutedEventArgs e)
    {           
        bool gotcapture = this.CaptureMouse();
        Mouse.AddLostMouseCaptureHandler(this, this.OnMouseLostCapture);
    }
            Point mouse_position_relative = Mouse.GetPosition(this);
        Point mouse_screen_position = popup.PointToScreen(mouse_position_relative);
        private void OnMouseLostCapture(object sender, MouseEventArgs e)
    {
        bool gotcapture = this.CaptureMouse();
        this.textblock.Text = "lost capture.";
    }

【问题讨论】:

    标签: wpf


    【解决方案1】:

    您的问题到底是什么?
    等待! 一种相对于屏幕定位弹出窗口的方法。见PlacementMode.AbsolutePoint
    这显示了飞来飞去的小开心脸:

    private Popup _popup;
    
    public Window1()
    {
        InitializeComponent();
    
        this.Loaded += OnLoaded;
    }
    
    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        _popup = new Popup
                  {
                      Child = new TextBlock {Text = "=))", Background = Brushes.White},
                      Placement = PlacementMode.AbsolutePoint,
                      StaysOpen = true,
                      IsOpen = true
                  };
        MouseMove += MouseMoveMethod;
        CaptureMouse();
    }
    
    private void MouseMoveMethod(object sender, MouseEventArgs e)
    {
        var relativePosition = e.GetPosition(this);
        var point= PointToScreen(relativePosition);
        _popup.HorizontalOffset = point.X;
        _popup.VerticalOffset = point.Y;
    }
    

    【讨论】:

      【解决方案2】:

      没关系,我意识到没有办法相对于屏幕定位 Popup,只能相对于包含它的 Visual。

      【讨论】:

        【解决方案3】:

        有多种方法可以在 WPF Window 之外获取鼠标位置的屏幕坐标。不幸的是,您需要添加引用才能使用它们中的任何一个,但这可能的。您可以在@FredrikHedblad 对How do I get the current mouse screen coordinates in WPF? 问题的回答中找到它们的示例。巧合的是,这个问题在你问这个问题的前几天就得到了回答,并在 21 分钟内放弃了。

        【讨论】:

          猜你喜欢
          • 2019-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多