본문 바로가기

Technique/C#

[WPF] 윈도우 리사이즈 할때 비율로 크기 조정하기

반응형


Maintaining Aspect Ratio when Resizing a WPF Window

 

일단... 두말하지않고 보시죠!! 소스코드!!


 


    internal class WindowAspectRatio

    {

        private double _ratio;


        private WindowAspectRatio(Window window)

        {

            _ratio = window.Width / window.Height;

            ((HwndSource)HwndSource.FromVisual(window)).AddHook(DragHook);

        }


        public static void Register(Window window)

        {

            new WindowAspectRatio(window);

        }


        internal enum WM

        {

            WINDOWPOSCHANGING = 0x0046,

        }


        [Flags()]

        public enum SWP

        {

            NoMove = 0x2,

        }


        [StructLayout(LayoutKind.Sequential)]

        internal struct WINDOWPOS

        {

            public IntPtr hwnd;

            public IntPtr hwndInsertAfter;

            public int x;

            public int y;

            public int cx;

            public int cy;

            public int flags;

        }


        private IntPtr DragHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)

        {

            if ((WM)msg == WM.WINDOWPOSCHANGING)

            {

                WINDOWPOS position = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));


                if ((position.flags & (int)SWP.NoMove) != 0 ||

                    HwndSource.FromHwnd(hwnd).RootVisual == null) return IntPtr.Zero;


                position.cx = (int)(position.cy * _ratio);


                Marshal.StructureToPtr(position, lParam, true);

                handeled = true;

            }


            return IntPtr.Zero;

        }

    }



그리고 또하나가 필요하겠죠... 

아래 표 처럼 추가 해주시면 되겠습니다...



using System;

using System.Windows;

using System.Windows.Interop;

using System.Runtime.InteropServices;




그리고 마지막으로 사용방법 이 있어야 겠죠?



XMAL쪽

 <Window ... SourceInitialized="Window_SourceInitialized" ... >

    ...

Window>


그리고 호출하는 함수!!!! 및 아규먼트!!


        private void Window_SourceInitialized(object sender, EventArgs e)

        {

            WindowAspectRatio.Register((Window)sender);


        }



아무쪼록 잘 사용하시고..


출처는........... 어디인지.. 기억이 안나서.


문제가 되면 삭제하도록 하겠습니다.!!!  알려주세요!~


반응형