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

查看:142
本文介绍了在运行时的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 ?

推荐答案

这是pretty的容易做,在Windows每一个窗口必须是可调整大小的与生俱来的能力。它只是关闭了一个图片,你可以重新打开它通过侦听<一个href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645618%28v=vs.85%29.aspx">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.

添加一个新类到您的项目并粘贴下面所示的code。建立+构建。你会得到工具箱之上的新的控制,把它表单上。设置图像属性,你就设置试试吧。

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() & 0xffff, m.LParam.ToInt32() >> 16));
            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;
}

另外的非常的廉价的方式来获得调整大小的自由是给予控制一个可调整大小的边框。这适用于所有角落和边缘。复制粘贴此code到类(你不需要的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天全站免登陆