繁体   English   中英

WPF应用程序在按下鼠标右键时崩溃

[英]WPF application get crashed on pressing right mouse button

我实际上正在尝试在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();
        }



    }
}

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

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

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

我用过这些代码,它实际上有效

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);
            } 
      private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
      {
        e.handled = true;  //in your case, prevent right click crash.    
        this.DragMove();
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM