打开顶部的WPF窗口,但不要';使用Powershell时,不要总是保持领先

打开顶部的WPF窗口,但不要';使用Powershell时,不要总是保持领先,wpf,powershell,window,topmost,Wpf,Powershell,Window,Topmost,我在使用WPF时遇到了一个问题。当我打开窗口时,我希望它在所有其他程序的顶部打开,但我不希望它始终保持在顶部,只是初始打开。我知道将topmost设置为true会在top上打开(我在Xaml中有),但我似乎找不到一种方法在它打开后将其更改为false 这是一个带有WPF窗口的简单测试函数 function foo{ #Load Assembly and Library Add-Type -AssemblyName PresentationFramework $input

我在使用WPF时遇到了一个问题。当我打开窗口时,我希望它在所有其他程序的顶部打开,但我不希望它始终保持在顶部,只是初始打开。我知道将topmost设置为true会在top上打开(我在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

函数foo{
#加载程序集和库
添加类型-AssemblyName PresentationFramework
$inputXaml=@”
"@
#从Xaml中删除元素,以便可以对其进行转换
$inputXamlClean=$inputXaml-替换'mc:Ignorable=“d','-替换'x:N','N'-替换'x:Class=“.*”,'-替换'd:DesignHeight=“\d*?”,'-替换'd:DesignWidth=“\d*?”,''
[xml]$xaml=$inputXamlClean
#创建窗口
$XMLReader=(新对象System.Xml.XmlNodeReader$xaml)
$Window=[Windows.Markup.XamlReader]::加载($XMLReader)
#为窗口上的所有元素创建变量
$xaml.SelectNodes(“//*[@Name]”)|%{Set Variable-Name($\u.Name)-Value$Window.FindName($\u.Name)}
#OK按钮动作
$okBtn.Add\u单击({
$Window.Close()
})
#橱窗
$Window.ShowDialog()
}
福

如果XAML中未设置最顶端,则在脚本运行时,窗口将显示在顶部(假设没有其他窗口设置最顶端),其行为类似于普通桌面窗口,在该窗口中,使用鼠标或键盘聚焦其他窗口将导致窗口失去前景位置

因此,对于“仅在初始打开时”处于顶部的窗口,去掉最顶部属性或将其设置为false将起作用,再次假设没有其他窗口设置了最顶部属性。如果实际上还有其他窗口在争夺最顶端的位置,您可以使用
SetForegroundWindow
将其暂时置于顶端: