0

例如,我试图将 WPF 窗口(不是窗口内的控件)锚定到 TopRight,默认情况下,Windows 将所有窗口锚定到左上角。

我尝试了以下代码

    private void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
    {
        double delta = e.PreviousSize.Width - e.NewSize.Width;
        Left += delta;
    }

它可以工作,但是在快速大小变化(例如动画)期间窗口会卡住/闪烁

我试着用谷歌搜索它,但没有找到一个好的解决方案,我错过了什么吗?

4

1 回答 1

0

在这篇文章的帮助下,我设法解决了这个问题。

这是代码

public partial class MainWindow : Window
{
    private double right;

    public MainWindow()
    {
        InitializeComponent();
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);
        HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
        right = Left + Width;
        source.AddHook(WndProc);
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == (int)WindowMessage.WindowPositionChanging)
        {
            var windowPosition = (WindowPosition)Marshal.PtrToStructure(lParam, typeof(WindowPosition));
            bool isMove = !windowPosition.Flags.HasFlag(WindowPositionFlags.NoMove); //0x0002
            bool isSize = !windowPosition.Flags.HasFlag(WindowPositionFlags.NoSize); //0x0001

            if (isMove)
            {
                right = windowPosition.Left + windowPosition.Width;
            }
            else if (isSize)
            {
                windowPosition.Left = (int)(right - windowPosition.Width);
                windowPosition.Top = (int)Top;
                windowPosition.Flags = (WindowPositionFlags)((int)windowPosition.Flags & 0xfffd); //remove the NoMove flag
                Marshal.StructureToPtr(windowPosition, lParam, true);
            }

        }
        return IntPtr.Zero;
    }

希望它可以帮助某人

于 2013-01-04T10:00:23.407 回答