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

UWP播放媒体时自动隐藏鼠标指针触发空引用异常求助

解决MediaPlayerElement播放后隐藏鼠标指针的空引用问题

嘿,我来帮你搞定这个问题!你遇到的空引用异常大概率是因为直接调用Window.Current.CoreWindow.PointerCursor = null时,Window.Current.CoreWindow还没初始化完成,或者你在非UI线程执行了这个操作。结合你的版本(最低Creators Update,目标Fall Creators Update),我给你一套完整的解决方案:

核心思路

  • 监听MediaPlayerElement的媒体播放开始事件,启动定时器延迟隐藏鼠标
  • 操作CoreWindow前先做空值检查,避免空引用
  • 监听鼠标移动事件,在用户操作时恢复指针并重启定时器
  • 确保所有UI操作都在UI线程执行

完整代码实现

首先,在你的页面XAML里给MediaPlayerElement设置命名:

<MediaPlayerElement x:Name="MyMediaPlayerElement" Source="ms-appx:///Assets/YourMediaFile.mp4" />

然后在页面的代码后台(.xaml.cs)添加以下逻辑:

private DispatcherTimer _cursorHideTimer;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);
    
    // 绑定媒体打开事件
    MyMediaPlayerElement.MediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
    // 绑定鼠标移动事件,用于恢复指针
    Window.Current.CoreWindow.PointerMoved += CoreWindow_PointerMoved;
    
    // 初始化定时器,设置延迟时间(这里是3秒,可按需调整)
    _cursorHideTimer = new DispatcherTimer
    {
        Interval = TimeSpan.FromSeconds(3)
    };
    _cursorHideTimer.Tick += CursorHideTimer_Tick;
}

private void MediaPlayer_MediaOpened(object sender, EventArgs e)
{
    // 媒体开始播放时启动定时器
    _cursorHideTimer.Start();
}

private void CursorHideTimer_Tick(object sender, object e)
{
    // 先判空再操作,彻底避免空引用异常
    if (Window.Current?.CoreWindow != null)
    {
        // 隐藏鼠标指针
        Window.Current.CoreWindow.PointerCursor = null;
        // 定时器触发后停止,直到下次鼠标移动重启
        _cursorHideTimer.Stop();
    }
}

private void CoreWindow_PointerMoved(object sender, PointerEventArgs e)
{
    if (Window.Current?.CoreWindow != null)
    {
        // 如果当前指针是隐藏状态,恢复箭头指针
        if (Window.Current.CoreWindow.PointerCursor == null)
        {
            Window.Current.CoreWindow.PointerCursor = new CoreCursor(CoreCursorType.Arrow, 0);
        }
        // 重启定时器,无操作后再次隐藏
        _cursorHideTimer.Start();
    }
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);
    
    // 页面离开时清理资源,避免内存泄漏
    _cursorHideTimer?.Stop();
    _cursorHideTimer = null;
    
    MyMediaPlayerElement.MediaPlayer.MediaOpened -= MediaPlayer_MediaOpened;
    Window.Current.CoreWindow.PointerMoved -= CoreWindow_PointerMoved;
}

关键注意点

  • 空值检查:每次访问Window.Current.CoreWindow前都用?.做空值判断,这是解决你空引用异常的核心
  • UI线程保障:DispatcherTimer本身就在UI线程执行,所以不需要额外切换线程
  • 资源清理:页面导航离开时一定要取消事件订阅和停止定时器,防止内存泄漏
  • 版本兼容性:你的目标版本是Fall Creators Update(16299),最低Creators Update(15063),这套代码完全兼容这两个版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:39:37