0

The title says it all, I have this code:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

const UInt32 WM_CLOSE = 0x0010;

and here's what I added to Form1_Load:

IntPtr windowPtr = FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad");
            if (windowPtr == IntPtr.Zero)
            {
                MessageBox.Show("Window not found");
                return;
            }

            SendMessage(windowPtr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);

so I added the code above to the Form1_Load function, and it actually works, it closes notepad when I open my program, but my question is, how to make the function repeat, like close notepad whenever it opens and not only on Form1_Load ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
MiRaN
  • 641
  • 1
  • 6
  • 11
  • [Writing automation to wait for a window to be created (and dismiss it)](http://blogs.msdn.com/b/oldnewthing/archive/2014/02/17/10500645.aspx) – GSerg May 01 '15 at 12:33
  • @GSerg I tried that, it just does nothing, it didn't close it, tried with notepad, Run and a lot other... – MiRaN May 01 '15 at 13:58
  • It does work as is with the Run dialog, provided you replace the `"Run"` literal with the caption of this dialog as it appears in your language of Windows. For Notepad, because it does not have a Cancel button that this code presses, you need to write a different closing code. My point however was that this is your way to get a notification when a new window is created. You can use your existing code as the event handler. – GSerg May 01 '15 at 16:26

1 Answers1

-1

You have to enumerate the windows yourself: EnumWindows and in the return procedure check if the title is the same as what you want (hardcoding 'Untitled' might not be the best way by the way). Alternatively traverse the window graph yourself with GetWindow, starting at the first desktop child and iterate the siblings from there.

Also you don't need the IntPtr version of FindWindow, you can pass null as a string parameter and it accomplishes the same.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • The OP is asking at what event the enumeration must be performed. They don't need `EnumWindows` either because they already have `FindWindow`. – GSerg May 01 '15 at 12:37
  • At what event? I read his question as asking how to repeat the function to close multiple Notepads, not just the first one. – Blindy May 01 '15 at 12:40
  • They close all notepads. Then the user opens another notepad. They want to close it too. – GSerg May 01 '15 at 12:59