c# 윈도우즈 폼즈의 form 잔기술들

폼 클래스의 위치

폼 클래스 코드는 네임스페이스에서 제일 위에 있어야 한다. 폼 클래스 코드 위에 다른 클래스 코드가 있으면 디자이너가 열리지 않는다. 디자이너는 파일의 첫 번째 클래스를 이용하여 작동하기 때문이다. 그러나 이거는 디자이너의 문제일 뿐이지 빌드의 문제는 아니다. 따라서 디자이너를 쓸 수 없을 뿐 빌드는 제대로 된다.

The designer could not be shown for this file because none of the classes within it can be designed. The designer inspected the following classes in the file: The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again.
– visual studio error message

폼 만들고 제어하기

부모 폼이 자식 폼을 만들고 자식 폼이 부모 폼을 제어하는 예제다. 자식 폼이 부모 폼을 제어하려면 자식 폼이 만들어질 때 컨스트럭터를 통해 부모 폼의 인스턴스를 받아서 부모 폼을 특정해야 한다. 그냥 만들기만 하면 자식 폼의 입장에서는 어떤 게 부모 폼인지 알 수가 없다. 아래 코드는 자식 폼을 먼저 만든 다음에 코딩해야 한다.

namespace WinFormsApp1
{
    public partial class Form2 : Form
    {
        Form1 MainForm;

        public Form2(Form1 form1)
        {
            InitializeComponent();

            MainForm = form1;
        }

        private void Form2_Click(object sender, EventArgs e)
        {
            MainForm.Text = "12345";
        }
    }
}

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Form2 form2 = new Form2(this);

            form2.Show();
        }
    }
}

스냎라인과 폼의 패딩

윈도우즈 폼즈의 디자이너로 비주얼 컨트롤을 만들고 움직여 보면 컨트롤들 사이에 줄이 생겼다 사라졌다 한다. 이걸 snapline이라 한다. 스냎라인은 컨트롤의 위치를 정하거나 컨트롤들 사이의 거리를 정할 때 도움이 된다. 스냎라인의 길이는 두 컨트롤들 사이의 마진과 패딩의 합이다. 그러나 폼의 패딩 값에 대해 주의해야 할 게 있다. 예를 들어 버튼을 만들어 폼의 왼쪽 위 구석으로 가까이 움직이면 12-12에 놓인다. 폼 패딩의 기본 값은 0-0-0-0이고 버튼 마진의 기본 값은 3-3-3-3이므로 버튼은 원칙적으로 3-3에 놓여야 하지만 그렇지 않다. 이런 문제는 폼 패딩의 값이 0-0-0-0일 때에는 9-9-9-9로 처리되기 때문이다.

The snapline’s distance from the right border is the sum of the control’s Margin property and the form’s Padding property values.
Note – If the form’s Padding property is set to 0,0,0,0, the Windows Forms Designer gives the form a shadowed Padding value of 9,9,9,9. To override this behavior, assign a value other than 0,0,0,0.
Walkthrough: Arrange controls on Windows Forms using snaplines