用户如何在运行时在 winforms 中调整控件的大小 [英] How can user resize control at runtime in winforms

查看:28
本文介绍了用户如何在运行时在 winforms 中调整控件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个图片框.

现在我想要的是用户应该能够随意调整图片框的大小.但是,我不知道如何开始这件事.我已经搜索过互联网,但信息很少.

Now what i want is that user should be able to resize the pictureBox at will. However i have no idea on how to even start on this thing. I have searched internet however information is scarce.

谁能至少指导我从哪里开始?

Can anybody at least guide me on where to start ?

推荐答案

这很容易做到,Windows 中的每个窗口都有天生的可调整大小的能力.它只是为 PictureBox 关闭,您可以通过侦听 WM_NCHITTEST 消息.您只需告诉 Windows 光标位于窗口的一角,您就可以免费获得其他一切.您还需要绘制一个把手,以便用户清楚拖动角将调整框的大小.

This is pretty easy to do, every window in Windows has the innate ability to be resizable. It is just turned off for a PictureBox, you can turn it back on by listening for the WM_NCHITTEST message. You simply tell Windows that the cursor is on a corner of a window, you get everything else for free. You'll also want to draw a grab handle so it is clear to the user that dragging the corner will resize the box.

向您的项目添加一个新类并粘贴如下所示的代码.构建+构建.您将在工具箱顶部获得一个新控件,将其放在表单上.设置 Image 属性,您就可以尝试了.

Add a new class to your project and paste the code shown below. Build + Build. You'll get a new control on top of the toolbox, drop it on a form. Set the Image property and you're set to try it.

using System;
using System.Drawing;
using System.Windows.Forms;

class SizeablePictureBox : PictureBox {
    public SizeablePictureBox() {
        this.ResizeRedraw = true;
    }
    protected override void OnPaint(PaintEventArgs e) {
        base.OnPaint(e);
        var rc = new Rectangle(this.ClientSize.Width - grab, this.ClientSize.Height - grab, grab, grab);
        ControlPaint.DrawSizeGrip(e.Graphics, this.BackColor, rc); 
    }
    protected override void WndProc(ref Message m) {
        base.WndProc(ref m);
        if (m.Msg == 0x84) {  // Trap WM_NCHITTEST
            var pos = this.PointToClient(new Point(m.LParam.ToInt32()));
            if (pos.X >= this.ClientSize.Width - grab && pos.Y >= this.ClientSize.Height - grab)
                m.Result = new IntPtr(17);  // HT_BOTTOMRIGHT
        }
    }
    private const int grab = 16;
}

另一种非常免费调整大小的方法是给控件一个可调整大小的边框.这适用于所有角落和边缘.将此代码粘贴到类中(您不再需要 WndProc):

Another very cheap way to get the resizing for free is by giving the control a resizable border. Which works on all corners and edges. Paste this code into the class (you don't need WndProc anymore):

protected override CreateParams CreateParams {
    get {
        var cp = base.CreateParams;
        cp.Style |= 0x840000;  // Turn on WS_BORDER + WS_THICKFRAME
        return cp;
    }
}

这篇关于用户如何在运行时在 winforms 中调整控件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆