반응형

* C# 컨트롤 이름으로 찾아 컨트롤 배열 처럼 사용 하기 예제...

 

메인화면

전체 소스코드

Form1.cs

 

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

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

        private void Form1_Load(object sender, EventArgs e)
        {

            //컨트롤 이름으로 찾아서 컨트롤 배열 처럼 사용 하기...
            //폼안에 컨트롤들 Panel 안에 있던 GroupBox 안에 있던 상관 없이 접근 가능
            
            for (int iCount = 1; iCount <= 10; iCount++)
            {
                this.FindByName<Button >("Button" + iCount.ToString()).Text = "Test" + iCount.ToString();
                this.FindByName<CheckBox>("CheckBox" + iCount.ToString()).Text = "Test" + iCount.ToString();
                this.FindByName<Label>("Label" + iCount.ToString()).Text = "Test" + iCount.ToString();
            }


            //아래의 소스코드 처럼 Panel 안에 있는 컨트롤들을 찾아서 Text 를 바꾸는 예제
            //계층적임.
            int iSample = 0;

            //각각 Panel GroupBox 안에 있는 컨트롤 접근
            //foreach (Control ct in panel1.Controls)
            //{
            //    CheckBox ch = ct as CheckBox;
            //    ch.Text = iSample.ToString();
            //    iSample += 1;
            //}

            //foreach (Control ct in groupBox1.Controls)
            //{
            //    Label lb = ct as Label;
            //    lb.Text = iSample.ToString();
            //    iSample += 1;
            //}

            //폼 안에 컨트롤 접근 -> Panel 및 GroupBox 찾아서 그 안에 있는 컨트롤 접근
            foreach (Control ct in this.Controls)
            {
                //타입이 Panel 이면...
                if (ct.GetType().Name.ToLower() == "panel")
                {
                    Panel pnl = ct as Panel;
                    foreach (Control ct1 in pnl.Controls)
                    {
                        CheckBox ch = ct1 as CheckBox;
                        ch.Text = iSample.ToString();
                        iSample += 1;
                    }
                }
                //타입이 GroupBox 이면...
                else if (ct.GetType().Name.ToLower() == "groupbox")
                {
                    GroupBox gb = ct as GroupBox;
                    foreach (Control ct2 in gb.Controls)
                    {
                        Label lb = ct2 as Label;
                        lb.Text = iSample.ToString();
                        iSample += 1;
                    }
                }
                
                //이 부분 어차피 접근이 안되는 부분... 
                else if (ct.GetType().Name.ToLower() == "label")
                {
                    Label lb = ct as Label;
                    lb.Text = "123213213213213";
                }

            }

        }
    }
}

 

 

 

Panel 이나 GroupBox 에 있는 컨트롤도 접근이 가능 한 이유는 Form1.Designer.cs 파일을 열어 보게 되면

아래의 그림과 같습니다.

 

System.Reflection.FieldInfo[] fis = obTarget.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

=> 이 구문을 풀어서 설명 하면서 GroupBox 나 Panel 에 있는 컨트롤도 접근 가능 한 이유도 같이 설명 하겠습니다.

     //Object 클래스 객체 타입을 얻어 옴...

     Type tp = obTarget.GetType();

 

     //Object 클래스 객체 안의 Private 변수들을 FieldInfo 배열로 받아 오기

     //전달 인자로 Flags 값이 NonPublic 이면 Private 변수들만 Public 이면 Public 변수들만 얻어 오게 됨.

     // 여기서 위 그림과 같이 Form1 디자이너에 선언된 필드들(즉 Private 변수들)을 얻어 오게 됩니다. 

     System.Reflection.FieldInfo[] fis = tp.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

 

     //아래의 그림처럼 브레이크를 걸어 fis배열 변수를 확인 해 보면...

 

     //사용자가 찾을려는 변수 이름을 얻어 리턴 변수 객체...
     System.Reflection.FieldInfo fi = null;

 

    //찾을 컨트롤 이름과 대조 해서 
     for (int iIndex = 0; iIndex < fis.Length; iIndex++)

      {
            //맞다면...
            if (fis[iIndex].Name.ToLower() == strName.ToLower())
            {
                 fi = fis[iIndex];

                 //사용자가 찾을려는 변수 객체를 찾았으니 For문 빠져 나오기...
                 break;
            }
       }

 

* 예제 실행 결과

 

 

 

 

 

//폼 안에 컨트롤 접근 -> Panel 및 GroupBox 찾아서 그 안에 있는 컨트롤 접근
            foreach (Control ct in this.Controls)
            {
                //타입이 Panel 이면...
                if (ct.GetType().Name.ToLower() == "panel")
                {
                    Panel pnl = ct as Panel;
                    foreach (Control ct1 in pnl.Controls)
                    {
                        CheckBox ch = ct1 as CheckBox;
                        ch.Text = iSample.ToString();
                        iSample += 1;
                    }
                }
                //타입이 GroupBox 이면...
                else if (ct.GetType().Name.ToLower() == "groupbox")
                {
                    GroupBox gb = ct as GroupBox;
                    foreach (Control ct2 in gb.Controls)
                    {
                        Label lb = ct2 as Label;
                        lb.Text = iSample.ToString();
                        iSample += 1;
                    }
                }
                
                //이 부분 어차피 접근이 안되는 부분... 
                else if (ct.GetType().Name.ToLower() == "label")
                {
                    Label lb = ct as Label;
                    lb.Text = "123213213213213";
                }

            }

  위 구문 처럼... 계층적으로 접근

* Panel.Controls 나 this.Controls 로 찾는 방식이랑은 틀림

ex) Panel1 에 Label 1,2,3,4,5 가 있고 Pannel2 에 Label 6,7,8,9 가 있음

   Panel1.Controls 로 Label12345 를 찾고 Panel2.Controls 로 6789 를 찾아야 됨.



 

https://kdsoft-zeros.tistory.com/10

 

[VBNET] 컨트롤 배열처럼 사용 하기(Controls Arrary)

VB6 처럼 VBNET 도 컨트롤 배열처럼 사용 하기 VB6 은 컨트롤 배열작성시 인덱스 가 정수형으로 사용 Label(1) Label(2) Label(3) Label(4) Label(5) Label(6)~ for iCount to 6 Label(iCount).Text ="" Next 하지..

kdsoft-zeros.tistory.com

 

반응형
반응형

* C# 시간 체크 (Time Check) 예제...

 

메인화면

전체 소스 코드

Form1.cs

 

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

namespace CSharp_TimeCheck
{
    public partial class Form1 : Form
    {
        bool bClick = false;
        DateTime dtClick ;

        bool bThread = true;
        System.Threading.Thread thMain;

        public Form1()
        {
            InitializeComponent();

            //크로스 스레드 오류 방지
            CheckForIllegalCrossThreadCalls = false;

            thMain = new System.Threading.Thread(new System.Threading.ThreadStart (Thread_Tick));

			//1. 첫번째 방법 : 스레드
            //이 스레드를 백그라운드로 지정 할 것인지 포어 그라운드로 지정 할 것인지...
            //true: 백그라운드 스레드 , false: 포어그라운드
            //기본은 false 포어그라운드
            //thMain.IsBackground = true;
            thMain.Start();
            
            //2. 두번째 방법 : 윈도우 타이머
            //타이머가 돌아가는 시간
            //timer1.Interval  = 300;
            //timer1.Start();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //스레드 객체가 null 이 아니면...
            bThread = false;
            
            if (thMain != null)
            {
                //스레드가 돌아가고 있으면
                if (thMain.IsAlive)
                {
                    //강제 종료
                    thMain.Abort();
                }

                thMain = null;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dtClick = DateTime.Now;
            bClick = true;
        }

        private double After_Time(DateTime dtNow, DateTime dtBefore)
        {
            TimeSpan ts = dtNow - dtBefore;
            return ts.TotalSeconds;
        }

		//스레드 이벤트...
        void Thread_Tick()
        {
            while (bThread)
            {
                if (bClick)
                {
                    label1.Text = string.Format("{0:##0}", After_Time(DateTime.Now, dtClick));
                }


                System.Threading.Thread.Sleep(100);
            }
        }
        
        //타이머 이벤트...
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (bClick)
            {
                label1.Text = string.Format("{0:##0}", After_Time(DateTime.Now, dtClick));
            }
        }

    }
}

* 예제 결과 

 

 

 

 

https://kdsoft-zeros.tistory.com/22

 

[C#] 크로스 스레드 (Cross Thread) 예제

* 크로스 스레드 - 자신의 스레드가 아닌 다른 스레드가 그 컨트롤에 접근했었을 때 발생하는 오류 * 해결 방법 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using..

kdsoft-zeros.tistory.com

 

반응형
반응형

* C# PC 비프음 (Beep) 예제...

 

전체 소스 코드

Form1.cs

 

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

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

        private void Button1_Click(object sender, EventArgs e)
        {
            Console.Beep(262, 400); //도
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            Console.Beep(294, 400); //레
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            Console.Beep(330, 400); //미
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            Console.Beep(349, 400); //파
        }

        private void Button5_Click(object sender, EventArgs e)
        {
            Console.Beep(392, 400); //솔
        }

        private void Button6_Click(object sender, EventArgs e)
        {
            Console.Beep(440, 400); //라
        }

        private void Button7_Click(object sender, EventArgs e)
        {
            Console.Beep(494, 400); //시
        }

        private void Button8_Click(object sender, EventArgs e)
        {
            Console.Beep(523, 400); //도
        }
    }
}

 

 

 

반응형
반응형

* VBNET PC 비프음 (Beep) 예제...

 

전체 소스 코드

Form1.vb

 

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Console.Beep(262, 400)  '도
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Console.Beep(294, 400)  '레
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Console.Beep(330, 400)  '미
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Console.Beep(349, 400)  '파
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Console.Beep(392, 400)  '솔
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Console.Beep(440, 400)  '라
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        Console.Beep(494, 400)  '시
    End Sub

    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
        Console.Beep(523, 400)  '도
    End Sub
End Class

 

반응형
반응형

* VBNET API 윈도우 (Window) 창 찾기 예제...

 

메인화면

전체 소스 코드

Form1.vb

 

Imports System.Runtime.InteropServices

Public Class Form1
    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
     Private Shared Function FindWindow( _
          ByVal lpClassName As String, _
          ByVal lpWindowName As String) As IntPtr
    End Function

    Declare Function SetForegroundWindow Lib "user32" Alias "SetForegroundWindow" (ByVal hwnd As Integer) As Integer
    Declare Function ShowWindowAsync Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer


    Private Const SW_WINDOW_NORMAL As Integer = 1
    Private Const SW_WINDOW_MINIMIZED As Integer = 2
    Private Const SW_WINDOW_MAXIMIZED As Integer = 3

    Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        ' 윈도우 타이틀명으로 핸들을 찾음.
        Dim hWnd As IntPtr = FindWindow(Nothing, TextBox1.Text)

        If Not hWnd.Equals(IntPtr.Zero) Then
            ' 윈도우가 최소화 되어 있다면 활성화 
            ShowWindowAsync(hWnd, SW_WINDOW_NORMAL)

            ' 윈도우에 포커스를 줘서 최상위로 만든다
            SetForegroundWindow(hWnd)
        End If
    End Sub
End Class

* 예제 결과

 

반응형
반응형

* C# API 윈도우 창 이름으로 윈도우 창 찾기 예제... (Window Form Search)

 

메인화면

 

전체 소스 코드

Form1.cs

 

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

using System.Runtime.InteropServices;

namespace CSharp_API윈도우창_찾기
{
    public partial class Form1 : Form
    {

        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        private const int SW_WINDOW_NORMAL = 1;
        private const int SW_WINDOW_MINIMIZED = 2;
        private const int SW_WINDOW_MAXIMIZED = 3;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 윈도우 타이틀명으로 핸들을 찾음.
            IntPtr hWnd = FindWindow(null, textBox1.Text);

            if (!hWnd.Equals(IntPtr.Zero))
            {
                // 윈도우가 최소화 되어 있다면 활성화 
                ShowWindowAsync(hWnd, SW_WINDOW_NORMAL);

                // 윈도우에 포커스를 줘서 최상위로 만든다
                SetForegroundWindow(hWnd);
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            //텍스트 박스에 Enter 키 입력이 들어 오면
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(null, null);
            }
        }
    }
}

 

 

* 예제 결과

 

반응형
반응형

* VBNET API 다른 응용 프로그램 실행 시키기 예제 : ShellExecuteA

 

메인화면

전체 소스 코드

Form1.vb

 

Public Class Form1

    Public Declare Function ShellExecuteA Lib "shell32.dll" ( _
    ByVal hWnd As IntPtr, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Integer) As IntPtr

    Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        '탐색기 실행 시키기...
        ShellExecuteA(Me.Handle, "open", "explorer.exe", "", "", 4)
    End Sub

    Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
        '계산기 실행 시키기...
        ShellExecuteA(Me.Handle, "open", "calc.exe", "", "", 4)
    End Sub

    Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click
        '실행 파일 오픈...
        Dim ofd As OpenFileDialog = New OpenFileDialog

        ofd.Filter = "EXE File (*.exe) | *.exe"

        '실행 파일 열기...
        If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
            '선택된 실행 파일 실행...
            ShellExecuteA(Me.Handle, "open", ofd.FileName, "", "", 4)
        End If

    End Sub
End Class

 

 

* 예제 결과

 

 

마지막 실행 파일 오픈 버튼 : 바로기가 또는 EXE 파일을 오픈 하여 그 프로그램이 실행 되는 모습을 보실 수 있습니다.


 

https://kdsoft-zeros.tistory.com/105

 

[C#] [API] 다른 응용 프로그램 실행 시키기 : ShellExecute ()

* C# 다른 응용 프로그램 실행 시키기 예제... 전체 소스 코드 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using Syste..

kdsoft-zeros.tistory.com

 

반응형
반응형

* C# 다른 응용 프로그램 실행 시키기 예제...

 

메인화면

전체 소스 코드

Form1.cs

 

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

using System.Runtime.InteropServices;

namespace CSharp_API다른프로그램실행시키기
{
    public partial class Form1 : Form
    {
        [DllImport("Shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //탐색기 실행하기...
            ShellExecute(this.Handle, "open", "explorer.exe", "", "", 4);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //계산기 실행하기...
            ShellExecute(this.Handle, "open", "calc.exe", "", "", 4);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //실행 시킬 파일 열기...
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "EXE File(*.exe) | *.exe";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                ShellExecute(this.Handle, "open", ofd.FileName , "", "", 4);
            }

        }
    }
}

 

using System.Runtime.InteropServices; <- 선언 후 

아래와 같이 API 함수를 선언 해 줍니다.

[DllImport("Shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

 

* 예제 결과

 

 

마지막 실행 파일 오픈 버튼 : 바로기가 또는 EXE 파일을 오픈 하여 그 프로그램이 실행 되는 모습을 보실 수 있습니다.

 

 

반응형

+ Recent posts