0

I created a c# winform application. It opens a new window (without borders, like a popup if this matters) which should always stay on top of the main form. The window is opened by a thread:
Task.Run(() => ...
in the constructor of the new form I tried to add :

this.TopMost = true;

Sometimes the window goes in the background of the main form. And sometimes i can't even open it from the taskbar. I click on it and nothing happens.

  • There are no other applications with a window open
  • I tried it on Windows 7 and 10 (different pc's)
  • I tried to call following method from form.load (which to be honest I have no idea what it does exactly) :
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static  UInt32 SWP_NOSIZE = 0x0001;
public static  UInt32 SWP_NOMOVE = 0x0002;
public static  UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

Nothing helped. Does someone have an idea?

bd123456
  • 26
  • 1
  • 7
  • Please show the code where you open that second form. Why exactly are you using a second thread? Is something like `secondFormInstance.Show(this);` or `secondFormInstance.ShowDialog(this);` not enough for you? If you do that, you won't even have to set the `TopMost` property. – 41686d6564 stands w. Palestine May 18 '19 at 17:44
  • Note that when you open a form on another thread (if you have to), it needs to be a UI (`STA`) thread. See [this](https://stackoverflow.com/a/4700057/4934172) or [this](https://stackoverflow.com/a/47438795/4934172). – 41686d6564 stands w. Palestine May 18 '19 at 17:52
  • the second form (PopUp) is called by a thread (some kind of listener for OPCUA Data). When the read data change then the Form should open in foreground but without blocking the main form. I open it by by contructing the object and then myPopUp.ShowDialog(); – bd123456 May 18 '19 at 17:53
  • This seems like an [XY problem](http://xyproblem.info/) but in any case, please include [edit] your question and include _that_ code; make sure it's a [Minimal, Reproducible Example](https://stackoverflow.com/help/reprex). – 41686d6564 stands w. Palestine May 18 '19 at 18:03
  • Creating a form on a worker thread requires advanced Winforms skills. There are a bunch of controls you cannot use since they are apt to cause deadlock. It is never required, don't do it. Create an owned window with the Show(owner) overload, it always stays on top of its owner. – Hans Passant May 18 '19 at 18:29
  • thanks to you two, I will try to change the structure of my code, so that it's not the worker who opens (owns) the window, but the main ui thread. If this doesn't help, i'll try to minimize the project, retest it and edit my question with this code. I didn't think that it could be a thread problem, so I did no research on it. – bd123456 May 18 '19 at 19:46

0 Answers0