我的 WPF 應用程式(不是主視窗)中有一個單一的視窗實體。由于它的結構,這個視窗只有在主視窗關閉時才會關閉;如果用戶關閉此視窗,它將變為隱藏狀態。當我單擊主視窗中的某個影像時,我想要第二個視窗的以下行為:
- 如果視窗被隱藏并且影像被單擊,我想在所有視窗的頂部顯示它(但不是通過設定
Topmost = true,我只想在頂部顯示它,而不是永遠將它固定在頂部)。 - 如果視窗顯示在頂部,則無事可做。
- 如果視窗打開,但被其他視窗覆寫或最小化,我也想只在頂部顯示一次。
我目前擁有的:
// In some application class
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
if (App.Current.MyWindow == null)
{
App.Current.MyWindow = WeightImageWindowView.Instance;
}
App.Current.MyWindow.ShowTop();
}
...
// in MyWindow class
public void ShowTop()
{
this.Topmost = true;
this.Show();
if (this.WindowState == WindowState.Minimized)
{
this.WindowState = WindowState.Normal;
}
var a = this.Activate();
var b = this.Focus();
this.Topmost = false;
}
我嘗試一個一個地、成對地和一起使用所有這些命令,但沒有得到上述行為。
uj5u.com熱心網友回復:
WndHelper.BringToFront(this);
使用下面的助手,只需呼叫 bringtofront
public class WndHelper
{
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsIconic(IntPtr hWnd);
public static void HideWindow(Window window)
{
var wih = new WindowInteropHelper(window);
WndHelper.ShowWindow(wih.Handle, 0);
}
public static void BringToFront(Window window)
{
var wih = new WindowInteropHelper(window);
BringToFront(wih.Handle);
}
//If the window is minimized, then Restore must be run first
//Windows that are in the background are enough to set as Foreground
public static void BringToFront(IntPtr hWnd)
{
if (hWnd == IntPtr.Zero)
return;
try
{
if (WndHelper.IsIconic(hWnd)) //the window is minimized
{
WndHelper.ShowWindow(hWnd, 9); // SW_RESTORE = 9
WndHelper.SetForegroundWindow(hWnd); // set window to foreground
}
else
WndHelper.SetForegroundWindow(hWnd);
}
catch { }
}
}
uj5u.com熱心網友回復:
謝謝@Villiam!我找到了以下解決方案:
- 設定
MyWindow.ShowActivated = true; - 重寫
ShowTop方法為:
public void ShowTop()
{
if (this.WindowState == WindowState.Minimized)
{
this.WindowState = WindowState.Normal;
}
this.Topmost = true;
this.Show();
this.Topmost = false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/528387.html
標籤:C#wpf
