本文介绍了保持窗体的长宽比在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让一个表格有在调整大小时所保存的固定纵横比?

How can I make a form have a fixed aspect ratio that is preserved when it is resized?

我知道它可以通过重写来完成 OnSizeChanged 并手动修改[新]高度/宽度,但会导致闪烁,因为被称为事件之前将被重新调整一次(不匹配的宽高比的大小),然后再调整(以正确的纵横比)。有没有更好的办法?

I know it can be done by overriding OnSizeChanged and manually modifying the [new] Height/Width, but that causes flicker since it is resized once before the event is called (to a size not matching the aspect ratio) and then resized again (to the correct aspect ratio). Is there a better way?

推荐答案

一些代码来让你开始。关键是要对WM_SIZING消息作出响应,它可以让你改变窗口的矩形。此示例是粗糙的,你真的要注意的是由用户,可从m.WParam拖哪个角落或边缘。用户界面将永远是伟大的,你不能真正做任何合理的当用户拖动一个角落。让您的窗体的布局非常灵活,所以你不关心宽高比是真正的解决方案。当显示内容不适合非常滚动条让用户做正确的事情自动完成。

Some code to get you started. The key is to respond to the WM_SIZING message, it allows you to change the window rectangle. This sample is crude, you really want to pay attention to which corner or edge is being dragged by the user, available from m.WParam. The user interface will never be great, you can't really do anything reasonable when the user drags a corner. Making your form's layout flexible enough so you don't care about aspect ration is the real solution. Displaying a scrollbar when the content doesn't fit pretty much lets the user do the Right Thing automatically.

using System.Runtime.InteropServices;
// etc..

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }
    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x216 || m.Msg == 0x214) { // WM_MOVING || WM_SIZING
            // Keep the window square
            RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
            int w = rc.Right - rc.Left;
            int h = rc.Bottom - rc.Top;
            int z = w > h ? w : h;
            rc.Bottom = rc.Top + z;
            rc.Right = rc.Left + z;
            Marshal.StructureToPtr(rc, m.LParam, false);
            m.Result = (IntPtr)1;
            return;
        }
        base.WndProc(ref m);
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }
}

这篇关于保持窗体的长宽比在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:36