Files
ADP/DeviceEditModule/Views/DialogMangerView.xaml.cs
2026-06-12 16:55:47 +08:00

82 lines
2.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using DeviceEditModule.ViewModels;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
namespace DeviceEditModule.Views
{
/// <summary>
/// DialogMangerView 代码后置。
/// 负责处理与 Window 相关的操作最小化ViewModel 通过事件通知,
/// 此处执行 P/Invoke绕过 WPF 在 AllowsTransparency=True 时禁止
/// 直接设置 WindowState.Minimized 的限制。
/// </summary>
public partial class DialogMangerView : UserControl
{
#region P/Invoke
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
/// <summary>SW_MINIMIZE最小化到任务栏。</summary>
private const int SW_MINIMIZE = 6;
/// <summary>SW_RESTORE激活并显示窗口。如果窗口最小化或最大化系统会将其还原到原始大小和位置。</summary>
private const int SW_RESTORE = 9;
#endregion
public DialogMangerView()
{
InitializeComponent();
// 在 Loaded 后订阅 ViewModel 的最小化请求事件
Loaded += (_, _) =>
{
if (DataContext is DialogMangerViewModel vm)
{
vm.MinimizeRequested += OnMinimizeRequested;
vm.RestoreRequested += OnRestoreRequested;
}
};
// 在 Unloaded 时取消订阅,防止内存泄漏
Unloaded += (_, _) =>
{
if (DataContext is DialogMangerViewModel vm)
{
vm.MinimizeRequested -= OnMinimizeRequested;
vm.RestoreRequested -= OnRestoreRequested;
}
};
}
private void OnRestoreRequested(object? sender, EventArgs e)
{
var window = Window.GetWindow(this);
if (window == null) return;
var hwnd = new WindowInteropHelper(window).EnsureHandle();
// 使用 Win32 API 强行恢复窗口,绕过 WPF 的 AllowsTransparency 限制
ShowWindow(hwnd, SW_RESTORE);
}
private void OnMinimizeRequested(object? sender, System.EventArgs e)
{
var window = Window.GetWindow(this);
if (window == null) return;
var hwnd = new WindowInteropHelper(window).EnsureHandle();
ShowWindow(hwnd, SW_MINIMIZE);
}
/// <summary>标题栏拖拽移动窗口。</summary>
private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
Window.GetWindow(this)?.DragMove();
}
}
}