0

I am calling Form.Show() on a certain Form and do some stuff afterwards which causes some updates on the Shown Form.

I want to move the this Window Form to another location with another Process during this time with SetWindowPos. Sadly the calling of SetWindowPos does exactly nothing. Probably because the is never idling?

Any Idea who to solve this Problem?

Thank you

Edit: some Code:

main.Show();
main.initBase(); //Takes 2-3 seconds
main.HideMainForm(); //Moves the form to (10000, 10000), to hide it (can't change that it's an old programm)

At the main.Shown event i have a call to another program which than calls SetWindowPos(pd.CurrentHandle, HWND_TOPMOST, r.X, r.Y, r.Width, r.Height, SetWindowPosFlags.DoNotChangeOwnerZOrder);

where r is the rectangle of the selected Display

I tried

EventHandler ev = new EventHandler((s, e) =>
{
    main.Close();
ev = new EventHandler((s2, e2) => { });
});

main.Shown += ev;       

main.ShowDialog();
main.Show();

which works fine but is just ugly code and i am trying to find a better solution.

lolsharp
  • 1
  • 2

2 Answers2

2

Two possibilities come to mind.

First, you say that at main.Shown, the external program calls SetWindowPos to move the window. And the code that shows the form takes 2 or 3 seconds to initialize and then moves the window off screen. Is it possible that the external program that calls SetWindowPos is executing before the call to HideMainForm?

What happens if you comment out the HideMainForm? Does the window get moved?

Second, you have:

SetWindowPos(
    pd.CurrentHandle, 
    HWND_TOPMOST,
    r.X, r.Y, r.Width, r.Height,
    SetWindowPosFlags.DoNotChangeOwnerZOrder);

It might be that the DoNotChangeOwnerZOrder flag is interfering with the HWND_TOPMOST request, and the function is failing. The documentation says:

A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed.

Granted, that doesn't say anything about the SWP_NOOWNERZORDER flag, but in the general case the owner's Z order will change if something is placed above it. So if you request that flag and the function can't ensure it, the function might fail.

You need to check the return value of SetWindowPos:

bool success = SetWindowPos(...);
if (!success)
{
    int err = Marshal.GetLastWin32Error();
    // the err value will give you information about why it failed.
}

For that to work, your DllImport must have SetLastError=true.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
0

Are you using Form.showDialog()?

It happens if so. Use Form.show() instead.

Abdul Saleem
  • 10,098
  • 5
  • 45
  • 45