You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinUI3自定义标题栏后窗口无法移动,求实现窗口拖动功能

解决WinUI3自定义标题栏后窗口无法拖动的问题

以下是两种实用的实现方案,可快速恢复窗口拖动功能:

方案一:通过鼠标按压事件触发窗口拖拽

在自定义标题栏的容器元素上监听PointerPressed事件,当左键按下时调用窗口的DragMove()方法:

  1. 在XAML中给标题栏容器绑定事件:
<Grid x:Name="CustomTitleBar" PointerPressed="CustomTitleBar_PointerPressed">
    <!-- 自定义标题栏内容:比如标题文本、控制按钮等 -->
</Grid>
  1. 在后台C#代码中实现事件处理逻辑:
private void CustomTitleBar_PointerPressed(object sender, PointerRoutedEventArgs e)
{
    // 仅响应鼠标左键按压
    if (e.GetCurrentPoint(null).Properties.IsLeftButtonPressed)
    {
        // 若当前代码在窗口类中,直接使用this即可
        this.DragMove();
        
        // 若代码在用户控件中,需先获取当前窗口实例:
        // var currentWindow = (MainWindow)Application.Current.Windows.First(w => w is MainWindow);
        // currentWindow.DragMove();
    }
}

方案二:利用WinUI3标题栏拖拽区域设置

如果你希望保留系统标题栏的交互逻辑,可通过设置标题栏的拖拽矩形区域来关联自定义标题栏:

  1. 在窗口初始化时配置标题栏:
public MainWindow()
{
    this.InitializeComponent();
    this.SizeChanged += Window_SizeChanged;
    SetupCustomTitleBarDragArea();
}

private void SetupCustomTitleBarDragArea()
{
    var appWindow = GetCurrentAppWindow();
    var titleBar = appWindow.TitleBar;
    
    // 允许内容延伸到标题栏区域
    titleBar.ExtendsContentIntoTitleBar = true;
    // 将自定义标题栏的区域设为可拖拽区域
    UpdateTitleBarDragRect();
}

// 获取当前窗口对应的AppWindow实例
private AppWindow GetCurrentAppWindow()
{
    var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
    var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hwnd);
    return AppWindow.GetFromWindowId(windowId);
}
  1. 窗口大小变化时更新拖拽区域(避免窗口缩放后拖拽失效):
private void Window_SizeChanged(object sender, WindowSizeChangedEventArgs e)
{
    UpdateTitleBarDragRect();
}

private void UpdateTitleBarDragRect()
{
    var appWindow = GetCurrentAppWindow();
    var titleBar = appWindow.TitleBar;
    
    // 根据自定义标题栏的实际尺寸更新拖拽矩形
    titleBar.SetDragRectangles(new Rect[] 
    {
        new Rect(0, 0, CustomTitleBar.ActualWidth, CustomTitleBar.ActualHeight)
    });
}

注意事项

  • 确保自定义标题栏的元素未设置IsHitTestVisible="False",否则无法触发鼠标事件。
  • 若标题栏内包含按钮(如最小化、关闭),需给这些按钮单独处理PointerPressed事件并标记e.Handled = true,避免触发拖拽逻辑。

内容的提问来源于stack exchange,提问作者ElprofetaMohammed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:10:09