0

I want to lock its Left coordinate.

This doesn't work as I want because there are glitches - flickering, because the window is moved back to Left=0. I'm more interested in something like LocationChanging to prevent it from ever moving left or right.

private void Window_LocationChanged(object sender, EventArgs e)
        {
            if (Left != 0) Left = 0;
        }
Greyshack
  • 1,901
  • 7
  • 29
  • 48
  • I think the user might find the fact that the window can't move left or right a little jarring. A prime example would be a situation where I have multiple monitors and want to move the program to a different monitor. – Gordon Allocman Mar 16 '16 at 17:49
  • Nah it's an application for a single purpose and I need this functionality. – Greyshack Mar 16 '16 at 18:03
  • Then you probably have to write your own MouseLeftButtonDown --> MouseMove event logic that updates the window as the mouse moves. Here is a [SO question that is somewhat similar to get your started](http://stackoverflow.com/questions/11703833/dragmove-and-maximize) – Gordon Allocman Mar 16 '16 at 18:09

1 Answers1

1

One option is to catch WM_MOVING window message and manipulate its lParam. Since WM_MOVING comes before the Window moves, you can adjust the next position as you wish.

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;
    }
}
emoacht
  • 2,764
  • 1
  • 13
  • 24