How to get the handle of the topmost form in a WinForm app?

前端 未结 5 1933
耶瑟儿~
耶瑟儿~ 2020-12-06 02:52

I have a WinForm app that has other child forms (not mdi). If the user presses \"Esc\" the topmost form should be closed even if it doesn\'t have the focus.

I can u

5条回答
  •  清歌不尽
    2020-12-06 03:36

    You could implement a singleton-like pattern in your topmost form, and provide a static property that returns the one instance of itself and simply close it.

       public class MainForm : Form
       {
          private static MainForm mainForm;
    
          public static MainForm { get { return mainForm; } }
    
          public MainForm()
          {
             mainForm = this;
          }
       }
    
    
       // When the ESC key is pressed...
       MainForm.MainForm.Close();
    

提交回复
热议问题