首页 > 解决方案 > 无边框 BlazorDesktop 拖动表单

问题描述

我创建了一个使用 FormBorderStyle.None 的 BlazorDesktop WinForms 应用程序,并且我的“TitleBar”是我的 Layout razor 组件中的 NavBar。我使用导航栏上的 onmousedown (也尝试过 ondragstart 和 ondrag )事件来调用我注入的服务,该服务调用 ReleaseCapture 和 SendMessage 来拖动表单。效果很好,但随机崩溃,没有错误,但控制台/事件查看器中出现一般错误

我将此服务注入 BlazorWebView

public interface IDragService
  {
      public void BeginDrag();
      public void EndDrag();
  }
  public class DragService : IDragService
  {
      public const int WM_NCLBUTTONDOWN = 0xA1;
      public const int WM_NCLBUTTONUP = 0xA2;
      public const int HT_CAPTION = 0x2;

      [System.Runtime.InteropServices.DllImport("user32.dll")]
      public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
      
      [System.Runtime.InteropServices.DllImport("user32.dll")]
      public static extern bool ReleaseCapture();

      private IntPtr MainHandle { get; init; }

      public DragService()
      {
          MainHandle = Application.OpenForms.OfType<Form1>().FirstOrDefault().Handle;
      }
      public void BeginDrag()
      {
          ReleaseCapture();
          SendMessage(MainHandle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); 
      }
      public void EndDrag()
      {
          ////ReleaseCapture();
          //SendMessage(MainHandle, WM_NCLBUTTONUP, HT_CAPTION, 0);
      }
  }

并设置我的布局剃刀组件,类似于:

@inherits LayoutComponentBase
@inject IDragService dragService

<div @onmousedown="onDragStart">testing</div>

<div>
    @Body
</div>

@code {
    private void onDragStart()
        => dragService.BeginDrag();

    //private void onDragEnd()
     //   => dragService.EndDrag();
}

它的效果惊人,但只是随机决定与程序“[13320] Test.exe”已退出,代码为 3221226525 (0xc000041d)。

有没有另一种方法可以做到这一点?我尝试通过 mainform.location 执行此操作,但这允许其他应用程序最终位于顶部,并且无法弄清楚如何将鼠标保持在相对于客户端的相同起点。

请帮忙。

标签: winformsblazoruser32.net-6.0blazor-desktop

解决方案


推荐阅读