티스토리 뷰

C#

7 TwoForms

김윤지. 2023. 4. 19. 14:17

024_TwoForms

 

두개의 Form을 디자인한다

Form1과 Form2는 클래스이므로 여러 개의 객체가 만들어진다.

즉, 새로 만든 Form1은 Form2를 불렀던 Form1이 아닌 새로운 Form1

>> Form1에서 Form2는 하나만 만들도록 코딩한다 (Form2에서 Form1 컨트롤 불가)

>> Form1이 Form2를 만들 때 생성자 메소드에 Form1을 매개변수로 넘겨주면 Form2에서도 Form1 컨트롤 가능

다음과 같이 Form1, Form2를 디자인 한다

 

Form1 코딩

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _024_TwoForms
{
  public partial class Form1 : Form
  {
    Form2 f = null;
    public Form1()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      if(f == null)
        f = new Form2(this);
      f.Show();
      //this.Hide();  // Form1은 숨긴다
    }

    private void button2_Click(object sender, EventArgs e)
    {
      label1.Text = f.textBox1.Text;
    }

    // Common 클래스에서 값을 가져오기
    private void button3_Click(object sender, EventArgs e)
    {
      MessageBox.Show(Common.str + "\n" + Common.value);
    }
  }

  public static class Common
  {
    public static string str = "";
    public static int value = 0;
  }
}

Form2 코딩

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _024_TwoForms
{
  public partial class Form2 : Form
  {
    Form1 f;
    public Form2(Form1 form)
    {
      InitializeComponent();
      f = form;
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //Form1 f = new Form1();
      f.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
      f.Text = textBox1.Text;
    }

    private void button3_Click(object sender, EventArgs e)
    {
      // Form1의 label1 Modifiers 수정
      f.label1.Text = textBox1.Text; 
    }

    // Form2에서 Common 클래스의 값을 지정
    private void button4_Click(object sender, EventArgs e)
    {
      Common.str = textBox1.Text;
      Common.value = 1024;
    }
  }
}

다음과 같이 코딩한다

'C#' 카테고리의 다른 글

9 WPF  (0) 2023.04.27
8 WPF  (0) 2023.04.26
6 Firebase  (0) 2023.04.13
5 함수, 타이머  (0) 2023.04.05
4 Form  (0) 2023.03.29
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함