How to get the size of a Winforms Form titlebar height?

后端 未结 5 490
独厮守ぢ
独厮守ぢ 2021-02-01 01:59

So if it\'s toolwindow or a minimizable form, I want to be able to get its height programmatically.

Is this possible? If so how?

相关标签:
5条回答
  • 2021-02-01 02:26

    You can determine titlebar height for both tool-windows and normal forms by using:

    Rectangle screenRectangle = this.RectangleToScreen(this.ClientRectangle);
    
    int titleHeight = screenRectangle.Top - this.Top;
    

    Where 'this' is your form.

    ClientRectangle returns the bounds of the client area of your form. RectangleToScreen converts this to screen coordinates which is the same coordinate system as the Form screen location.

    0 讨论(0)
  • 2021-02-01 02:33

    This will get you the TitleBarsize:

    form.ClientRectangle.Height - form.Height;
    
    0 讨论(0)
  • 2021-02-01 02:34

    There is an additional wrinkle in case your form is a view in an MDI application. In that case RectangleToScreen(this.ClientRectangle) returns coordinates relative not to Form itself (as one might expect) but with respect to MainForm which hosts MDIClient control hosting the Form.

    You may to account for that by

    Point pnt = new Point(0, 0);
    Point corner = this.PointToScreen(pnt); // upper left in MainFrame coordinates
    Point origin = this.Parent.PointToScreen(pnt); // MDIClient upperleft in MainFrame coordinates
    int titleBarHeight = corner.Y - origin.Y - this.Location.Y;
    
    0 讨论(0)
  • 2021-02-01 02:41

    In my case, I had to change the height of the form so that it was just below one of the controls, I noticed that

      int titleHeight = this.Height - screenRectangle.Height;
    

    returns 39 while the accepted answer:

      int titleHeight =  screenRectangle.Top - this.Top;
    

    returns 31

    maybe because of form's bottom border.

    0 讨论(0)
  • 2021-02-01 02:46

    To fix S. Norman's answer that simply has his minuend and subtrahend switched, the following is the simplest answer:

    int HeightOfTheTitleBar_ofThis = this.Height - this.ClientRectangle.Height;

    BTW, the standard hard coded title bar is 25dpi which is the minimum height and can be changed to a maximum of 50dpi.

    OK OK,... yes, it is technically incorrect As stated by Cody Grey but it works and should get the same answer as the accepted answer. No need to create a rectangle.

    0 讨论(0)
提交回复
热议问题