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

PowerShell WPF视频播放器:如何实现单显示器中央全屏显示?

解决方案

问题根源在于原代码使用GetDeviceCaps获取的是**整个虚拟桌面(多显示器组合)**的尺寸,而非主显示器单独的参数,导致窗口跨显示器显示,且定位逻辑错误。以下是修正后的代码:

<#
.NOTES 
    获取主显示器参数,实现视频播放器在主显示器全屏显示并铺满整个屏幕
#>

# 引用必要程序集,用于获取主显示器信息
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.ComponentModel

# 获取主显示器的分辨率与位置信息
$primaryScreen = [System.Windows.Forms.Screen]::PrimaryScreen
$screenWidth = $primaryScreen.Bounds.Width
$screenHeight = $primaryScreen.Bounds.Height
$screenLeft = $primaryScreen.Bounds.Left
$screenTop = $primaryScreen.Bounds.Top

# WPF窗口XAML定义
[xml]$XAML = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PowerShell Video Player" 
        Width="$screenWidth" 
        Height="$screenHeight" 
        ResizeMode="NoResize"
        WindowStartupLocation="Manual"> <!-- 手动指定位置,避免系统自动定位到虚拟桌面中间 -->
    <Grid>
        <!-- 移除Margin,设置铺满整个窗口 -->
        <MediaElement Name="VideoPlayer" 
                      LoadedBehavior="Manual" 
                      UnloadedBehavior="Stop"
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Stretch" />
    </Grid>
</Window>
"@

# 视频文件路径
[uri]$VideoSource = "$env:TMP\z\e.mp4"

# 加载XAML并获取控件
$XAMLReader = (New-Object System.Xml.XmlNodeReader $XAML)
$Window = [Windows.Markup.XamlReader]::Load($XAMLReader)
$VideoPlayer = $Window.FindName("VideoPlayer")

# 设置视频参数并播放
$VideoPlayer.Volume = 100
$VideoPlayer.Source = $VideoSource
$VideoPlayer.Play()

# 手动设置窗口位置为显示器左上角(确保铺满整个主显示器)
$Window.Left = $screenLeft
$Window.Top = $screenTop

# 显示窗口
$Window.ShowDialog() | Out-Null

关键修改点

  • 替换屏幕信息获取方式:使用System.Windows.Forms.Screen.PrimaryScreen直接获取主显示器的分辨率和位置,避免虚拟桌面尺寸的干扰。
  • 手动控制窗口位置:将WindowStartupLocation设为Manual,并通过$Window.Left和$Window.Top绑定主显示器的起始坐标,确保窗口完全在主显示器内。
  • 优化MediaElement布局:移除多余的Margin和固定尺寸,改用Stretch对齐方式,让视频铺满整个窗口。

内容的提问来源于stack exchange,提问作者I am Jakoby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:27:32