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
{
///
/// DialogMangerView 代码后置。
/// 负责处理与 Window 相关的操作(最小化),ViewModel 通过事件通知,
/// 此处执行 P/Invoke,绕过 WPF 在 AllowsTransparency=True 时禁止
/// 直接设置 WindowState.Minimized 的限制。
///
public partial class DialogMangerView : UserControl
{
#region P/Invoke
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
/// SW_MINIMIZE:最小化到任务栏。
private const int SW_MINIMIZE = 6;
/// SW_RESTORE:激活并显示窗口。如果窗口最小化或最大化,系统会将其还原到原始大小和位置。
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);
}
/// 标题栏拖拽移动窗口。
private void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
Window.GetWindow(this)?.DragMove();
}
}
}