我想锁定它的左坐标。
这并不是我想要的,因为有毛刺 - 闪烁,因为窗口被移回到Left = 0。我对像LocationChanging这样的东西更感兴趣,以防止它向左或向右移动。
private void Window_LocationChanged(object sender, EventArgs e)
{
if (Left != 0) Left = 0;
}
答案 0 :(得分:1)
一个选项是捕获WM_MOVING窗口消息并操纵其lParam。由于WM_MOVING在窗口移动之前到来,您可以根据需要调整下一个位置。
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
public partial class MainWindow : Window
{
private const int WM_MOVING = 0x0216;
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private int _left;
private int _width;
public MainWindow()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
_left = (int)this.Left;
_width = (int)this.Width;
var handle = new WindowInteropHelper(this).Handle;
var source = HwndSource.FromHwnd(handle);
source.AddHook(new HwndSourceHook(WndProc));
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_MOVING)
{
var position = Marshal.PtrToStructure<RECT>(lParam);
position.left = _left;
position.right = position.left + _width;
Marshal.StructureToPtr(position, lParam, true);
}
return IntPtr.Zero;
}
}