【问题标题】:WPF application get crashed on pressing right mouse buttonWPF应用程序在按下鼠标右键时崩溃
【发布时间】:2017-11-18 15:31:03
【问题描述】:

我实际上正在尝试在 c# wpf 中制作 Jarvis AI 程序,但我在代码中遇到异常。实际上,问题是当我正在运行的应用程序上按下鼠标右键时,应用程序会卡住并崩溃,任何人都可以帮助我解决这个问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace jarvis
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }



    }
}

【问题讨论】:

    标签: c# wpf windows


    【解决方案1】:

    我不确定你想达到什么目的,但如果你想用鼠标左键移动窗口,只需添加条件:

    private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if(e.LeftButton == MouseButtonState.Pressed)
            this.DragMove();
    }
    

    在 DragMove() 方法中导致 InvalidOperationException 的其他鼠标按钮。 如果您想使用鼠标右键移动窗口,您必须为其编写自定义方法。

    【讨论】:

    • 实际上我的 wpf 应用程序有问题,当我在正在运行的应用程序上按鼠标右键时,它会卡住并崩溃。如何解决这个问题。
    • 尝试用我上面提到的代码替换 Grid_MouseDown 方法。这应该可以解决您的问题。
    【解决方案2】:

    我已经使用了这些代码,它确实有效

    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HT_CAPTION = 0x2;
    
    [DllImportAttribute("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    [DllImportAttribute("user32.dll")]
    public static extern bool ReleaseCapture();
    

    在你的表单鼠标按下事件中使用 ReleaseCapture 方法 像这样

    if (e.Button == MouseButtons.Left)
                {
                    ReleaseCapture();
                    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
                } 
    

    【讨论】:

      【解决方案3】:
            private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
            {
              e.handled = true;  //in your case, prevent right click crash.    
              this.DragMove();
            }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多