Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

winforms - How to prevent vertically resize in VB.NET Windows Forms

Working with Windows Forms, I wonder if there is some way to prevent vertically resize of the form. I would like to allow user to resize a form in all directions except vertically. Moreover, I would like to allow vertically resize in the upward direction, but not downward.

I have tried to use maximumsize by setting it to: Me.maximumsize = new size(0, me.height)

I set width to 0, because I want to allow user to change the form width.

Unfortunately it doesn't work.

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to be careful to allow the form to resize itself at startup. It is necessary to accommodate scaling needed on a machine that has a different video DPI setting or a different system font size. Or a user override that changed the height of the title bar. All of this is sorted out by the time the Load event runs. Thus:

protected override void OnLoad(EventArgs e) {
  Screen scr = Screen.FromControl(this);
  this.MinimumSize = new Size(this.MinimumSize.Width, this.Height);
  this.MaximumSize = new Size(scr.WorkingArea.Width, this.Height);
}

The next thing you ought to do is fix the behavior of the cursor when the user moves it on an edge of the window that allows resizing the window vertically. That's a bit ugly; you have to trap the WM_NCHITTEST message with WndProc and change the message return value:

protected override void WndProc(ref Message m) {
  base.WndProc(ref m);
  if (m.Msg == 0x84) {  // Trap WM_NCHITTEST
    switch (m.Result.ToInt32()) {
      case 12: m.Result = (IntPtr)2; break;  // HTTOP to HTCAPTION
      case 13: m.Result = (IntPtr)10; break; // etc..
      case 14: m.Result = (IntPtr)11; break;
      case 15: m.Result = (IntPtr)1; break;
      case 16: m.Result = (IntPtr)10; break;
      case 17: m.Result = (IntPtr)11; break;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...