본문 바로가기
Study/C#

C# Windows Forms 강의 18편: Process 클래스와 외부 프로그램 실행

by wawManager 2025. 2. 21.
728x90

1. 강의 개요

이번 강의에서는 Process 클래스를 사용하여 Windows Forms 애플리케이션에서 외부 프로그램을 실행하거나, 실행 중인 프로세스를 관리하는 방법을 학습합니다.
Process 클래스를 활용하면 애플리케이션에서 다른 프로그램과 상호작용하거나 명령줄 명령을 실행할 수 있습니다.


2. 학습 목표

  1. **Process.Start()**를 사용해 외부 프로그램 실행.
  2. 특정 파일을 기본 프로그램으로 열기.
  3. 실행 중인 프로세스 정보 얻기 및 종료.

3. Process 클래스

Process 클래스란?

Process 클래스는 운영 체제에서 실행 중인 프로세스를 제어하거나 새로운 프로세스를 시작하는 데 사용됩니다.

  • 특정 프로그램 실행 (예: 메모장, 브라우저).
  • 명령줄 명령 실행.
  • 프로세스 정보 얻기 및 종료.

Process 주요 메서드

메서드 설명 예제

Start() 지정된 파일 또는 프로그램 실행 Process.Start("notepad.exe");
Kill() 프로세스 종료 process.Kill();

Process 주요 속성

속성 설명 예제

ProcessName 프로세스 이름 string name = process.ProcessName;
StartTime 프로세스 시작 시간 DateTime startTime = process.StartTime;

4. 실습: Process 클래스 사용

요구사항

  1. "프로그램 실행" 버튼 클릭 시 메모장(Notepad) 실행.
  2. "URL 열기" 버튼 클릭 시 브라우저로 특정 URL 열기.
  3. "프로세스 목록 보기" 버튼 클릭 시 실행 중인 프로세스 목록을 ListBox에 표시.
  4. ListBox에서 선택한 프로세스를 종료.

폼 구성

컨트롤 타입 이름 텍스트 위치 크기

Button btnRunProgram "프로그램 실행" (20, 20) (120 x 30)
Button btnOpenUrl "URL 열기" (160, 20) (120 x 30)
Button btnViewProcesses "프로세스 목록 보기" (20, 60) (120 x 30)
ListBox listBoxProcesses (없음) (20, 100) (400 x 200)
Button btnKillProcess "프로세스 종료" (20, 310) (120 x 30)

코드 작성

Form1.cs

using System;
using System.Diagnostics;
using System.Windows.Forms;

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

        private void InitializeProcessDemo()
        {
            // "프로그램 실행" 버튼 클릭 이벤트
            btnRunProgram.Click += (sender, e) =>
            {
                Process.Start("notepad.exe");
            };

            // "URL 열기" 버튼 클릭 이벤트
            btnOpenUrl.Click += (sender, e) =>
            {
                string url = "https://www.google.com";
                Process.Start(new ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                });
            };

            // "프로세스 목록 보기" 버튼 클릭 이벤트
            btnViewProcesses.Click += (sender, e) =>
            {
                listBoxProcesses.Items.Clear();
                Process[] processes = Process.GetProcesses();
                foreach (var process in processes)
                {
                    listBoxProcesses.Items.Add($"{process.Id} - {process.ProcessName}");
                }
            };

            // "프로세스 종료" 버튼 클릭 이벤트
            btnKillProcess.Click += (sender, e) =>
            {
                if (listBoxProcesses.SelectedItem == null)
                {
                    MessageBox.Show("종료할 프로세스를 선택하세요.", "알림");
                    return;
                }

                // 선택한 프로세스 ID로 종료
                string selectedItem = listBoxProcesses.SelectedItem.ToString();
                int processId = int.Parse(selectedItem.Split('-')[0].Trim());
                try
                {
                    Process.GetProcessById(processId).Kill();
                    MessageBox.Show("프로세스가 종료되었습니다.", "알림");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"프로세스를 종료하는 중 오류가 발생했습니다: {ex.Message}", "오류");
                }
            };
        }
    }
}

디자이너 코드: Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
        private Button btnRunProgram;
        private Button btnOpenUrl;
        private Button btnViewProcesses;
        private ListBox listBoxProcesses;
        private Button btnKillProcess;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.btnRunProgram = new Button();
            this.btnOpenUrl = new Button();
            this.btnViewProcesses = new Button();
            this.listBoxProcesses = new ListBox();
            this.btnKillProcess = new Button();
            this.SuspendLayout();

            // btnRunProgram
            this.btnRunProgram.Location = new System.Drawing.Point(20, 20);
            this.btnRunProgram.Name = "btnRunProgram";
            this.btnRunProgram.Size = new System.Drawing.Size(120, 30);
            this.btnRunProgram.TabIndex = 0;
            this.btnRunProgram.Text = "프로그램 실행";
            this.btnRunProgram.UseVisualStyleBackColor = true;

            // btnOpenUrl
            this.btnOpenUrl.Location = new System.Drawing.Point(160, 20);
            this.btnOpenUrl.Name = "btnOpenUrl";
            this.btnOpenUrl.Size = new System.Drawing.Size(120, 30);
            this.btnOpenUrl.TabIndex = 1;
            this.btnOpenUrl.Text = "URL 열기";
            this.btnOpenUrl.UseVisualStyleBackColor = true;

            // btnViewProcesses
            this.btnViewProcesses.Location = new System.Drawing.Point(20, 60);
            this.btnViewProcesses.Name = "btnViewProcesses";
            this.btnViewProcesses.Size = new System.Drawing.Size(120, 30);
            this.btnViewProcesses.TabIndex = 2;
            this.btnViewProcesses.Text = "프로세스 목록 보기";
            this.btnViewProcesses.UseVisualStyleBackColor = true;

            // listBoxProcesses
            this.listBoxProcesses.FormattingEnabled = true;
            this.listBoxProcesses.ItemHeight = 20;
            this.listBoxProcesses.Location = new System.Drawing.Point(20, 100);
            this.listBoxProcesses.Name = "listBoxProcesses";
            this.listBoxProcesses.Size = new System.Drawing.Size(400, 200);
            this.listBoxProcesses.TabIndex = 3;

            // btnKillProcess
            this.btnKillProcess.Location = new System.Drawing.Point(20, 310);
            this.btnKillProcess.Name = "btnKillProcess";
            this.btnKillProcess.Size = new System.Drawing.Size(120, 30);
            this.btnKillProcess.TabIndex = 4;
            this.btnKillProcess.Text = "프로세스 종료";
            this.btnKillProcess.UseVisualStyleBackColor = true;

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(450, 360);
            this.Controls.Add(this.btnKillProcess);
            this.Controls.Add(this.listBoxProcesses);
            this.Controls.Add(this.btnViewProcesses);
            this.Controls.Add(this.btnOpenUrl);
            this.Controls.Add(this.btnRunProgram);
            this.Name = "Form1";
            this.Text = "Process 클래스 예제";
            this.ResumeLayout(false);
        }
    }
}

6. 실행 결과

  1. 프로그램 실행
    • "프로그램 실행" 버튼 클릭 시 메모장이 실행됩니다.
  2. URL 열기
    • "URL 열기" 버튼 클릭 시 기본 브라우저에서 구글 홈페이지가 열립니다.
  3. 프로세스 목록 보기
    • "프로세스 목록 보기" 버튼 클릭 시 실행 중인 프로세스 목록이 ListBox에 표시됩니다.
  4. 프로세스 종료
    • ListBox에서 프로세스를 선택하고 "프로세스 종료" 버튼 클릭 시 해당 프로세스가 종료됩니다.

7. 주요 개념 요약

  1. **Process.Start()**로 외부 프로그램 실행 또는 URL 열기 가능.
  2. **Process.GetProcesses()**로 실행 중인 모든 프로세스 정보를 가져올 수 있음.
  3. **Process.Kill()**로 특정 프로세스를 종료 가능.

 

728x90