簡體   English   中英

在頂部打開 WPF 窗口,但不要總是使用 Powershell 保持在頂部

[英]Open WPF Window on top, but don't always keep on top using Powershell

我在使用 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

如果在 XAML 中未設置 Topmost,則在運行腳本時該窗口將顯示在頂部(假設沒有其他設置了 Topmost 的窗口)並且其行為類似於普通桌面窗口,其中使用鼠標或鍵盤將焦點放在其他窗口上導致窗口失去前景位置。

因此,對於“僅初始打開”的窗口,刪除 Topmost 屬性或將其設置為 false 將起作用,再次假設沒有其他設置了 Topmost 的窗口。 如果實際上還有其他窗口在爭奪最上面的位置,您可以使用SetForegroundWindow將其暫時放在最上面:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM