【问题标题】:Open WPF Window on top, but don't always keep on top using Powershell在顶部打开 WPF 窗口,但不要总是使用 Powershell 保持在顶部
【发布时间】:2020-01-08 19:38:13
【问题描述】:

我在使用 WPF 时遇到了问题。当我打开窗口时,我希望它在所有其他程序之上打开,但我不希望它始终保持在最前面,只是最初的打开。我知道将 topmost 设置为 true 会在顶部打开(我在 Xaml 中有),但我似乎找不到在打开后将其更改为 false 的方法。

这是一个带有 WPF 窗口的简单测试函数。

function foo{
    #Load Assembly and Library
    Add-Type -AssemblyName PresentationFramework

    $inputXaml = @"
    <Window x:Class="SharepointCreateOpportunity.completeWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SharepointCreateOpportunity"
        mc:Ignorable="d"
        Title="Window Title" Height="250" MinHeight="250" MaxHeight="250" Width="500" MinWidth="500" MaxWidth="500" Topmost="True" WindowStartupLocation="CenterScreen" Background="Black" >

    <Grid>
        <Button Name="oKBtn" Content="OK" Margin="0,0,20,20" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="72" Height="23"/>
    </Grid>
</Window>
"@
    #Gets rid of elements from the Xaml so it can be converted
    $inputXamlClean = $inputXaml -replace 'mc:Ignorable="d"','' -replace "x:N",'N' -replace 'x:Class=".*?"','' -replace 'd:DesignHeight="\d*?"','' -replace 'd:DesignWidth="\d*?"',''
    [xml]$xaml = $inputXamlClean

    #Creates the Window
    $XMLReader = (New-Object System.Xml.XmlNodeReader $xaml)
    $Window = [Windows.Markup.XamlReader]::Load($XMLReader)

    #Creates variables for all the elements on the window
    $xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name ($_.Name) -Value $Window.FindName($_.Name)}

    #OK Button Action
    $okBtn.Add_Click({
        $Window.Close()
    })

    #Show window
    $Window.ShowDialog()
}

foo

【问题讨论】:

    标签: wpf powershell window topmost


    【解决方案1】:

    如果未在 XAML 中设置 Topmost,则该窗口将在脚本运行时显示在顶部(假设没有其他设置了 Topmost 的窗口),并且其行为类似于普通桌面窗口,其中鼠标聚焦于其他窗口否则键盘会导致窗口失去前景位置。

    因此,对于“只是初始打开”的窗口来说,去掉 Topmost 属性或将其设置为 false 将起作用,再次假设没有其他窗口设置了 Topmost。如果确实有其他窗口在争夺最高位置,您可以使用SetForegroundWindow 将其暂时置于最高位置:

    https://stackoverflow.com/a/12802050/4195823

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多