반응형

* C# WMI 를 이용한 현재 실행 중인 프로세스 조회 (Process Search) 

- WMI 를 사용하기 위해 참조 -> System.Management dll 을 추가 -> 소스 코드 using System.Management

 

메인화면

전체 소스 코드

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.Management;

namespace CSharp_NowProcess
{
    public partial class Form1 : Form
    {

        string strWMIQry = "Select Name, ProcessID, ExecutablePath, WorkingSetSize From Win32_Process";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //리스트뷰 아이템 초기화
            lv.Items.Clear();

            ManagementObjectSearcher oWMI = new ManagementObjectSearcher(new SelectQuery(strWMIQry));

            foreach (ManagementObject oItem in oWMI.Get())
            {
                try
                {
                    //리스트뷰에 디스플레이...
                    ListViewItem lvi = new ListViewItem();
					
                    //프로세스 이름
                    lvi.Text = oItem.GetPropertyValue("Name").ToString();
                    //프로세스 ID
                    lvi.SubItems.Add(oItem.GetPropertyValue("ProcessID").ToString());
                    //크기
                    lvi.SubItems.Add(string.Format("{0:00}", (double)int.Parse(oItem.GetPropertyValue("WorkingSetSize").ToString()) / 1024) + " KB");
                    //위치
                    lvi.SubItems.Add(oItem.GetPropertyValue("ExecutablePath").ToString());

                    lv.Items.Add(lvi);
                }
                catch (Exception)
                {
                }

            }


        }
    }
}

*예제 결과

 

결과화면

 

반응형
반응형

* C# WMI 를 이용한 윈도우 시작 시 시작되는 프로그램 조회 예제...

- WMI 를 사용하기 위해 참조 -> System.Management dll 을 추가 -> 소스 코드 using System.Management

 

메인화면

전체 소스 코드

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.Management;

namespace CSharp_WMIStartupProgram
{
    public partial class Form1 : Form
    {

        string strWMIQry2 = "SELECT * FROM Win32_StartupCommand";
        

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] strV = new string[3];

            ManagementObjectSearcher oWMI = new ManagementObjectSearcher(new SelectQuery(strWMIQry2));

			listView1.Items.Clear();
            foreach (ManagementObject oItem in oWMI.Get())
            {
                strV[0] = oItem.GetPropertyValue("Name").ToString();        //  프로그램명
                strV[1] = oItem.GetPropertyValue("Command").ToString();     // 프로그램의 FullName
                strV[2] = oItem.GetPropertyValue("Location").ToString();    // 레지스트리 경로

                ListViewItem lvi = new ListViewItem();
                lvi.Text = strV[0];
                lvi.SubItems.Add(strV[1]);
                lvi.SubItems.Add(strV[2]);

                listView1 .Items.Add(lvi);
            
            }
        }

    }
}

 

* 예제 결과

 

결과 화면

 

 

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

 

[VBNET] [WMI] 윈도우 시작 프로그램 조회 (Startup Program)

* VBNET WMI 를 이용한 윈도우 시작 시 시작되는 프로그램 조회 예제... 전체 소스 코드 Form1.vb 프로젝트 -> 참조 추가 -> System.Management dll 을 참조 추가 해 줍니다. Imports System.Management Public C..

kdsoft-zeros.tistory.com

 

반응형
반응형

* C# API 이용 인터넷 연결 체크 예제... (Internet Connect 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;

using System.Runtime.InteropServices;

namespace CSharp_InternetConnectCheck
{
    public partial class Form1 : Form
    {
        [DllImport("wininet.dll", SetLastError = true)]
        private extern static bool InternetGetConnectedState(out int lpdwFlags, int dwReserved);

        [Flags]
        enum ConnectionStates
        {
            Modem = 0x1,
            LAN = 0x2,
            Proxy = 0x4,
            RasInstalled = 0x10,
            Offline = 0x20,
            Configured = 0x40,
        }

        System.Threading.Thread thMain;
        bool bCheck = false;

        public Form1()
        {
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;
            thMain = new System.Threading.Thread(new System.Threading.ThreadStart (Thread_Tick));
            
            //백그라운드 스레드로 지정...
            thMain.IsBackground = true;
            button1.Text = "Internet Connect Check Start";
            bCheck = true;
            //스레드 시작...
            thMain.Start();
           


        }

        protected override void OnClosed(EventArgs e)
        {
      
            if (thMain != null)
            {
                //스레드가 돌고 있으면...
                if (bCheck )
                {
                    //강제종료...
                    thMain.Abort ();
                }
                //스레드가 일시 정지 상태이면...
                else
                {
                    //대기중인 스레드 종료...
                    thMain.Interrupt();
                }
                thMain = null;
            }

            GC.Collect();

            base.OnClosed(e);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!bCheck)
            {
                bCheck = true;
                //일시정지된 스레드 다시 시작
                thMain.Resume();
                button1.Text = "Internet Connect Check Start";
                
                
            }
            else
            {
                bCheck = false;
                //스레드 일시정지
                thMain.Suspend();
                button1.Text = "Internet Connect Check Stop";
                
            }
        }

        /// <summary>
        /// 인터넷 연결 상태
        /// </summary>
        /// <returns></returns>
        public static bool Get_InternetConnectedState()
        {
            int flage = 0;
            return InternetGetConnectedState(out flage, 0);
        }

        private void Thread_Tick()
        {
            while (true )
            {
                if (Get_InternetConnectedState())
                {
                    label1.Text = "인터넷 연결이 되어 있습니다.";
                }
                else
                {
                    label1.Text = "인터넷 연결이 끊어 졌습니다.";
                }

                System.Threading.Thread.Sleep(1000);
            }
        }

    }
}

API 선언

 

 

 

* 예제 결과

 

 

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# Text File Read 시 한글 깨짐 방지 예제...

 

메인화면

전체 소스코드

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_File
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "TXT File(*.txt) | *.txt";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                label1.Text = ofd.FileName;

                //File Read...
                //한글 깨짐
                //using (System.IO.StreamReader sr = new System.IO.StreamReader(label1.Text))
                //1. 첫번째 방법
                //using (System.IO.StreamReader sr = new System.IO.StreamReader(label1.Text, System.Text.Encoding.Default ))
                //2. 두번째 방법
                using (System.IO.StreamReader sr = new System.IO.StreamReader(label1.Text, System.Text.Encoding.GetEncoding(949)))
                {
                    textBox1.Text = sr.ReadToEnd();
                }


            }


        }
    }
}

 

*예제 결과

 

기본 파일 위치만 지정 했을 경우
파일 기본 위치 및 엔코딩 까지 지정했을 경우

 

 

 

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

 

[C#] File Create & Delete & Read & Write 예제

* 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.Wind..

kdsoft-zeros.tistory.com

 

반응형
반응형

* C# API 이용 컨트롤 (Control) 모서리 둥글게 만들기 예제...

 

메인화면

전체 소스 코드

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_RoundControl
{
    public partial class Form1 : Form
    {

        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int x1, int y1, int x2, int y2,
                                                int cx, int cy);
        [DllImport("user32.dll")]
        private static extern int SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool bRedraw);


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //15 로 전달 되어 있는 인자 -> 실제 모서리 둥글게 표현 하는 인자
            IntPtr ip = CreateRoundRectRgn(0, 0, label1.Width, label1.Height, 15, 15);
            int i = SetWindowRgn(label1.Handle, ip, true);

            IntPtr ip2 = CreateRoundRectRgn(0, 0, textBox1.Width, textBox1.Height, 15, 15);
            int i2 = SetWindowRgn(textBox1.Handle, ip2, true);

            this.Refresh();

        }
    }
}

 

* 예제 결과 

결과 화면

Button 클릭 시 위 그림의 빨간 테두리 안에 컨트롤들의 모서리가 둥글게 변하는 모습을 보실 수 있습니다.

반응형
반응형

* 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_숫자를한글로
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        #region 숫자를 한글로 읽기 변환 ex) 1542500 => 일백오십사만이천오백원
        public  string CalToHan(string strTmp)
        {
            int iTotalLength = strTmp.Length;
            int iLength = iTotalLength;
            byte[] cTmp = Encoding.ASCII.GetBytes(strTmp);
            string sTmp = "";

            for (int iCount = 0; iCount < iTotalLength; iCount++)
            {
                if (cTmp[iCount] - 48 != 0)
                {
                    sTmp += NumberHan(cTmp[iCount] - 48) + NumberUnit(iLength);
                }
                iLength -= 1;
            }
            sTmp += "원";
            return sTmp;
        }
        private  string NumberUnit(int iTmp)
        {
            string sTmp = "";
            switch (iTmp)
            {
                case 0:
                    {
                        sTmp = "";
                        break;
                    }
                case 1:
                    {
                        sTmp = "";
                        break;
                    }
                case 2:
                    {
                        sTmp = "십";
                        break;
                    }
                case 3:
                    {
                        sTmp = "백";
                        break;
                    }
                case 4:
                    {
                        sTmp = "천";
                        break;
                    }
                case 5:
                    {
                        sTmp = "만";
                        break;
                    }
                case 6:
                    {
                        sTmp = "십";
                        break;
                    }
                case 7:
                    {
                        sTmp = "백";
                        break;
                    }
                case 8:
                    {
                        sTmp = "천";
                        break;
                    }
                case 9:
                    {
                        sTmp = "억";
                        break;
                    }
                case 10:
                    {
                        sTmp = "십";
                        break;
                    }
                case 11:
                    {
                        sTmp = "백";
                        break;
                    }
                case 12:
                    {
                        sTmp = "천";
                        break;
                    }
            }
            return sTmp;
        }
        private  string NumberHan(int iTmp)
        {
            string sTmp = "";

            switch (iTmp)
            {
                case 0:
                    {
                        sTmp = "";
                        break;
                    }
                case 1:
                    {
                        sTmp = "일";
                        break;
                    }
                case 2:
                    {
                        sTmp = "이";
                        break;
                    }
                case 3:
                    {
                        sTmp = "삼";
                        break;
                    }
                case 4:
                    {
                        sTmp = "사";
                        break;
                    }
                case 5:
                    {
                        sTmp = "오";
                        break;
                    }
                case 6:
                    {
                        sTmp = "육";
                        break;
                    }
                case 7:
                    {
                        sTmp = "칠";
                        break;
                    }
                case 8:
                    {
                        sTmp = "팔";
                        break;
                    }
                case 9:
                    {
                        sTmp = "구";
                        break;
                    }
            }
            return sTmp;
        }
        #endregion

    }
}

 

-> Ascii 코드 값 숫자 0 -> 48 , 1->49 ~ 

 

 

*예제 결과

반응형
반응형

* C# IP Ping 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_PingCheck
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            try
            {

                System.Net.NetworkInformation.Ping Pping = new System.Net.NetworkInformation.Ping();
                System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();

                options.DontFragment = true;

                //전송할 데이터를 입력
                string strData = "123123123";
                byte[] buffer = ASCIIEncoding.ASCII.GetBytes(strData);

                int iTimeout = 120;
                //IP 주소를 입력
                System.Net.NetworkInformation.PingReply PRreply = Pping.Send(System.Net.IPAddress.Parse(TextBox1.Text), iTimeout, buffer, options);

                if (PRreply.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    MessageBox.Show("Ping Check Success...", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }

                else
                {
                    MessageBox.Show("Ping Check Failed...", "확 인", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

            catch(Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
    }
}

 

*예제 결과

 

 

 

반응형
반응형

* C# API 를 이용 PC 종료 시키기 예제...

 

메인화면

전체 소스코드

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_PCExit
{
    public partial class Form1 : Form
    {

        [DllImport("advapi32.dll")]
        public static extern void InitiateSystemShutdown(string lpMachineName,        //컴퓨터 이름 \\\\127.0.0.1
                                                         string lpMessage,            //종료 전 사용자에게 알릴 메시지
                                                         int dwTimeout,               //종료까지 대기 시간
                                                         bool bForceAppsClosed,       //프로그램 강제 종료 여부(False -> 강제 종료)
                                                         bool bRebootAfterShutdown);  //시스템 종료 후 다시 시작 여부(true -> 다시 시작)



        bool bClick = false;
        DateTime dtClick;

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

        bool bCheck = false;

        public Form1()
        {
            InitializeComponent();

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

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

            //1. 첫번째 방법 : 스레드
            thMain.IsBackground = true;
            thMain.Start();

            //2 두번째 방법
            //10초 뒤 종료
            //System.Diagnostics.Process.Start("shutdown", "/s /f /t 10");
            //label2.Text = "10";

        }

        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)
                {
                    label2.Text = string.Format("{0:##0}", After_Time(DateTime.Now, dtClick));

                    if (After_Time(DateTime.Now, dtClick) >= 5 && !bCheck)
                    {
                        InitiateSystemShutdown("\\\\127.0.0.1" , null, 0, false, false );
                        bCheck = true;
                    }

                }


                System.Threading.Thread.Sleep(100);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (thMain != null)
            {
                if (thMain.IsAlive)
                {
                    thMain.Abort();
                }
                thMain = null;
            }
        }

    }
}

 

위 그림에서 보듯이 5초 후 PC 가 종료 되게끔 구현이 되어 있습니다. 5초는 임의로 정한 숫자일 뿐이고

나중에 사용자가 설정을 할 수 있게 하게 되면 얼마든지 시간 설정하여 자유롭게 PC 종료 하는 프로그램을

만들 수 있습니다. 

 

* 두번째 방법으로는 아래와 같이 Diagnostics.Process 를 이용 PC 종료 예제 입니다.

/*
피시 강제 종료
System.Diagnostics.Process.Start("shutdown.exe", "-s -f /t 60");      //-t 초 즉 60초 뒤에 PC 종료...
피시 종료 카운트다운 때 아래 명령을 날리면 종료가 취소됨
System.Diagnostics.Process.Start("shutdown.exe", "-a");
피시 재시작
System.Diagnostics.Process.Start("shutdown.exe", "-r");
피시 로그오프
System.Diagnostics.Process.Start("shutdown.exe", "-l");
 
*/

 

 

*예제 결과

 

 

 

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

 

[C#] 시간 체크 (Time Check)

* C# 시간 체크 (Time Check) 예제... 전체 소스 코드 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq;..

kdsoft-zeros.tistory.com

 

반응형

+ Recent posts