2

I have a simple question. How can I access aero snap programmatically from my C# code. Like, if I click a button "Snap Left", I want my program window to snap to the left, just like when its drug over there manually. I looked all over SO, but all the questions seem to be about aero snap not working with a form, and keeping it from snapping a form. Not programmatically snapping a form. I'm happy to use interloping. Thanks

FrostyFire
  • 3,212
  • 3
  • 29
  • 53

1 Answers1

5

What you can do, assuming you are on Windows 7, is to send the AreoSnap Keypress to the currently active window.

This codeproject has a very nice article on doing just that.

Also check out this SO question.

It seems that one way to do this is use sendmessage in User32.dll.

Here is an example of this, assuming "notepad" is the program you want to send the keystroke to:

[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);
private void button1_Click(object sender, EventArgs e)
{
    Process [] notepads=Process.GetProcessesByName("notepad");
    if(notepads.Length==0)return;            
    if (notepads[0] != null)
    {
        IntPtr child= FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);
        SendMessage(child, 0x000C, 0, textBox1.Text);
    }
}
Community
  • 1
  • 1
CC Inc
  • 5,842
  • 3
  • 33
  • 64
  • Well that's a cool idea! I think that should work. Thanks. +1 – FrostyFire Nov 11 '12 at 22:12
  • 1
    The example code appears to be sending WM_SETTEXT to Notepad's Edit control, setting its text. This has nothing to do with simulating Aero snap. My testing indicates that SendMessage will not trigger Aero snap, so I fail to understand why this answer was accepted or upvoted. I'm guessing that, as with other system hotkeys, Win-Left/Right is handled by the system and not by the target window procedure, so simulating it requires sending keystrokes at a higher level, such as with the SendInput API. – Lexikos Jul 06 '19 at 04:12