C# 기초

C# 2010. 12. 19. 18:29



C# 기본
//콘솔 제어
Console.Title = "콘솔 타이틀";
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
//Console.Beep();
Console.SetCursorPosition(0, 0);

//출력 {인덱스, 폭:형식}
Console.WriteLine("숫자 : {0, -16:F16}, 문자 : {1}", int.MaxValue, "string");

//키 입력
Console.Write("input key : ");
ConsoleKeyInfo cki = Console.ReadKey();
if (cki.Key == ConsoleKey.LeftArrow)
Console.WriteLine("key press LeftArrow");
else
Console.WriteLine("is not LeftArrow");

//입력
Console.Write("input str : ");
string input = Console.ReadLine();

Console.ResetColor();

ENUM
enum Order { First = 1, Second = 2, Third = 4 }
..
Order ord = Order.First;
Console.WriteLine(ord.ToString());
Console.WriteLine((Order)Enum.Parse(typeof(Order), "Third"));
ref, out
함수 인자가 클래스인 경우 reference가 전달되며 구조체나 native 변수인 경우 값이 복사되어 전달된다.(java처럼)
method1(ref int i)인 경우 c++의 & 처럼 call-by-reference로 동작한다.
method2(out int i)인 경우 ref와 동일하나 출력용이므로 변수가 초기화되지 않아도 된다.

public static void method1(ref int i) { i = 3; }
public static void method2(out int i) { i = 3; }
..
int num1 = 0;
method1(ref num1); Console.WriteLine(num1);
int num2;
method2(out num2); Console.WriteLine(num2);

params : 가변길이 인수
public static void TestParams(params int[] num)
{
foreach (var i in num)
Console.WriteLine(i);
}
..
TestParams(1, 2, 3, 4);
TestParams(new int[] { 5, 6, 7, 8 });

형변환 : Convert 클래스
int num = Convert.ToInt32("10");
Console.WriteLine(num);

checked, unchecked
: overflow/underflow 검사여부를 코드로 지정
checked
{
byte b = 255;
Console.WriteLine(b++);
}
project properties > Build > ouput - Advanced.. 에서 Check for arithmetic overflow/underflow 를
체크하면 항상 checked로 동작한다.
boxing, unboxing
stack에 저장되는 native 변수와 heap 에 저장되는 Object 간의 변환. (java 처럼)
int i = 1;
object o = i; //boxing
int i = (int)o; //unboxing

class partial
: 클래스 정의를 분할하여 여러군데에서 정의할 수 있다.
partial class Test
{
public int i;
}
partial class Test
{
public void method1() { i++; }
}

access modifier (접근 지정자)
private, protected, public (C++이나 java와 동일)
internal : 같은 assembly 안에서만 접근 가능. default
protected internal : 같은 assembly 안이나 파생 클래스 에서만 접근 가능.

그 외 modifier (지정자)
static, const, virtual, abstract, extern (c++과 동일)
readonly : 초기화 가능한 읽기 전용 멤버 변수
override : override하는 메소드
new : 부모 메소드가 sealed 로 지정되어 오버라이드 하지 못하는 경우 새로 정의할 때 사용.
sealed : 봉인 클래스. 메소드를 오버라이드 하지 못하게 하거나 클래스를 상속하지 못하도록 함. 항상 override 와 같이 사용됨.
volatile : 최적화를 하지 않는 필드

property (프로퍼티)
: 클래스 멤버변수의 Get/Set 메소드를 간편하게 생성하고 사용하는 방법
class Test
    {
        int num;
        public int Num //public이므로 get,set은 private나 protected 지정자를 사용할 수 있음
        {
            get { return num; }
            set { num = value; }  
        }
    }
..
Test test = new Test();
Console.WriteLine(test.Num = 3); //3으로 set하고 get한 결과 출력
위와 같이 단순한 프로퍼티는 자동 구현 프로퍼티로 대체할 수 있따.
ex) public int Num {get; set;}

indexer (인덱서)
: Object를 배열처럼 사용하도록 해줌.
    class Test
    {
        int num;
        public int this[string str] //오버로딩 혹은 this[int a, int b] 가능
        {
            get { 
                if (str.Equals("hi"))   return num;
                else                    return 0;
            }
            set {
                if (str.Equals("hi"))   num = value;
                else                    num = -1;
            }
        }
    }
..
Test test = new Test();
Console.WriteLine(test["hi"]=3);

operator overloading (연산자 오버로딩)
오버로딩 가능한 연산자 : +, -, *, /, %, ++, --, &, |, ^, <<, >>, ~, ==, !=, <, >, <=, >=, !
오버로딩 불가한 연산자 : =, [], &&, ||
([]는 indexer를 사용하며 &&, || 는 쇼트 서킷(short circuit) 기능에 의한 부작용으로 금지)
* short circuit(쇼트 서킷) : (i==1 || i==2) 처럼 앞쪽 조건으로 뒤쫏 조건의 실행여부가 판단되는 연산자

    class Test
    {
        public int num;
        public Test(int i) { num = i; }
        public static Test operator +(Test a, Test b)
        {
            return new Test(a.num + b.num);
        }
        public static Test operator +(Test a, int b)
        {
            return new Test(a.num + b); ;
        }
    }
..
Test a = new Test(1);
Test b = new Test(2);
Console.WriteLine(a + b);
Console.WriteLine(c.num + 1);

casting operator overloading (캐스팅 연산자 오버로딩)

    class Test
    {
        public int num;
        public Test(int i) { num = i; }
        public static explicit operator Test(int a) //명시적 캐스팅 사용
        {
            return new Test(a + 2);
        }
        public static implicit operator int(Test a) //암시적 캐스팅 사용: 컴파일러가 자동변환
        {
            return a.num+1;
        }
    }
..
Test a = (Test)1;   //명시적 캐스팅
int i = a;          //암시적 캐스팅
Console.WriteLine(i);

is 연산자 : java의 instance of 처럼 변수 타입 판별
    class Test {}
    class Test1 : Test {}
..
Test1 a = new Test1();
if (a is Test)
Console.WriteLine("is Test class");

as 연산자 : 해당타입이라면 형 변환을 수행하며 아닌 경우 null 반환
    class Test {}
    class Test1 : Test {}
..
Test1 a = new Test1();
Test b = a as Test; //as 연산자 사용
결국 as 연산자는 다음 처럼 동작한다.
Test b;
if (a is Test) b = (Test)a;
else b = null;
inheritance (상속)
상속시 C++ 처럼 콜론(:) 을 사용한다. (class Child : Parent)
자식 클래스에서 부모 클래스 메소드 호출 및 변수 사용은 base(base.method() 및 base.a)를 사용한다. (java의 super 처럼..)
부모 클래스의 virtual로 정의된 메소드만 자식 클래스에서 override 키워드로 오버라이딩 가능하다.
다른 OOP 언어 처럼 interface, abstract 지원

foreach 문을 사용할 수 있는 클래스 작성 예제
방법1. IEnumerable과 IEnumerator 를 구현하여 작성.
(각 인터페이스는 GetEnumerator() 와 Current(), MoveNext(), Reset()를 구현한다.)
방법2. Iterator 로 구현 : GetEnummerator()만을 구현하며 yield로 순서대로 리턴한다.
방법1 샘플
class Test : IEnumerable
{
public int[] arr;
public Test(params int[] input) { arr = input; }
public IEnumerator GetEnumerator() { return new TestEnum(this); }
}
class TestEnum : IEnumerator
{
Test cls;
int cnt;
public TestEnum(Test t)
{
cls = t;
Reset();
}
public bool MoveNext()
{
if (cnt < cls.arr.Length-1)
{
cnt++;
return true;
}
else    return false;
}
public object Current
{
get
{
if (cnt > -1) return cls.arr[cnt];
else          return null;
}
}
public void Reset() { cnt = -1; }
}
..
Test a = new Test(1, 2, 3, 4);
foreach (int i in a)
Console.WriteLine(i);
방법2 샘플
class Test
{
public int[] arr;
public Test(params int[] input) { arr = input; }
public IEnumerator GetEnumerator()
{
foreach (int i in arr)
yield return i;
}
}
..
Test a = new Test(1, 2, 3, 4);
foreach (int i in a)
Console.WriteLine(i);
**. yield 키워드
iterator 블록에서 열거자 개체에 값을 제공하거나 반복 종료를 알리기 위해 사용.
yield return <expression>; 혹은 yield break;

Deep Copy (깊은 복사)
: ICloneable 의 Clone() 구현하여 사용

    class Test : ICloneable //인터페이스 구현
    {
        public int i;
        public object Clone() //인터페이스 메소드 구현
        {
            Test ret = new Test();
            ret.i = this.i;     //deep copy
            return ret;
        }
    }
..
Test a = new Test();
a.i = 11;
//Test b = a;   //잘못된 코드
Test b = (Test)a.Clone(); //deep copy
b.i = 22;
Console.WriteLine("a.i="+ a.i +", b.i="+ b.i);


IDisposable
: 자원 해제를 위해 사용. 
클래스의 destructor는 GC에 의해 호출되므로 언제 호출될지 예측할 수 없다.
중요한 자원을 해제해야할 경우 IDisposable의 Dispose()를 구현하도록 규약하고 있으며
직접 호출하여 사용한다.

    class Test : IDisposable
    {
        bool isDisposed = false;
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);  //이 객체는 destructor가 동작하지 않도록 함
        }
        ~Test()
        {
            Dispose(false);
        }
        public virtual void Dispose(bool bManage)   //실수로 Dispose()를 호출하지 않아도 자원해제가 보장되도록 함.
        {
            if (isDisposed)
                return;
            else
                isDisposed = true;

            if (bManage) //관리해야할 자원만 따로 해제해야 하는 경우
            {
                //자원 해제
            }
            Console.WriteLine("자원 해제 완료");
        }
    }
..
Test a = new Test();
//a.Dispose();
using 구문
: 자동으로 Dispose()가 호출됨을 보장해주는 코드
위의 IDisposable을 구현한 class를 다음과 같이 사용.
using (Test a = new Test())
{
Console.WriteLine("hi");
} //이곳을 빠져나가면서 Test 클래스의 Dispose()를 자동으로 호출함.
결국 실행되는 코드는 다음과 같다.
try
{
Test a = new Test();
Console.WriteLine("hi");
}
finally
{
a.Dispose();
}

Delegate (델리게이트)
: C++의 메소드 포인터와 같은 개념

delegate int dMethod1(string s);
class Program
{
public int method1(string s) { Console.WriteLine(s); return 10; }

..
dMethod1 m1;
m1 = (new Program()).method1;
m1("hi");
m1 = new dMethod1((new Program()).method1); //위와 동일
m1("bye");

Delegate Covariance, Contravariance
class Parent{}
class Child : Parent { }

class Program
{
public delegate Parent dGetParent();
public delegate Child dGetChild();

public static Parent getParent() { return new Parent(); }
public static Child  getChild()  { return new Child(); }


public delegate void dSetParent(Parent cls);
public delegate void dSetChild(Child cls);

public static void setParent(Parent cls) {}
public static void setChild (Child cls)  {}
..
/*
Covariance (공변성)
: delegate의 리턴 타입이 실제 메소드보다 child class인 경우 에러.
*/
dGetParent GetParent;
GetParent = getParent;
GetParent = getChild;

dGetChild GetChild;
//GetChild = getParent; //error
GetChild = getChild;

/*
Contravariance (비공변성)
: delegate의 인자 타입이 실제 메소드보다 parent class인 경우 에러
*/
dSetParent SetParent;
SetParent = setParent;
//SetParent = setChild; //error

dSetChild SetChild;
SetChild = setParent;
SetChild = setChild;

Delegate 이용한 CALLBACK 구현

    public delegate void callbackMethod(int i);
    public static void method1(int i) { Console.WriteLine(i); }
    public static void test(callbackMethod m)
    {
        m(10);
    }
..
test(method1);  
Multicast Delegate (멀티캐스트 델리게이트)
: 메소드 목록을 갖을 수 있음
    public delegate void dMethod(int i);
    public static void method1(int i) { Console.WriteLine("method1 " + i); }
    public static void method2(int i) { Console.WriteLine("method2 " + i); }
..
dMethod d = null;
d += method1;
d += method2;
d(22); //metho1과 method2가 같이 불려짐

event (delegate)
: delegate를 이벤트 형식으로 사용시 좀 더 편한 방법을 제공.
메세지를 객체지향적으로 캡슐화. 

class Test
{
public delegate void dClick();
public event dClick ClickEvent;
public void OnClick()
{
if (ClickEvent != null)
ClickEvent();
}
}
class Program
{
static void DoIt()
{
Console.WriteLine("Do it");
}

static void Main(string[] args)
{
Test t = new Test();
t.ClickEvent += DoIt;
t.OnClick();
}
}
anonymous method (delegate)
: 간단히 delegate 함수를 직접 작성하여 사용하는 방법
delegate int dMethod(int a, int b);
class Program
{
static void Main(string[] args)
{
dMethod m1 = delegate(int a, int b) { return a * b; };
Console.WriteLine(m1(2,4));
}
}
reflect 및 string, StringBuilder 지원
정규표현식 지원
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string str = "start, test@test.com, end";
MatchCollection Find = Regex.Matches(str, @"\bt\S+m\b");
foreach (Match m in Find)
Console.WriteLine(m.Value);
}
}

Collection
ArrayList, HashTable, Stack, Queue, List<T>, LinkedList, Dictionary
Utility class
DateTime, Math, Environment
Generic
ex) public static void test<T>(T n)  { Console.WriteLine(n); }
ex) 
class Test<T>
{
private T var;
public T Var
{
get { return var; }
set { var = value; }
}
}
..
Test<int> t = new Test<int>();
t.Var = 23;
Console.WriteLine(t.Var);

Generic 제약조건 
where T:struct - T는 값 타입이어야 하며 참조 타입은 쓸 수 없음. (단, Nullable 타입 불허)
where T:classs - T는 참조 타입이어야 하며 값 타입을 쓸 수 없음.
where T:new() - T는 디폴트 생성자가 있어야 한다. (다른 조건과 사용시 맨 뒤에 지정)
where T:base - T는 base로 부터 파생된 클래스여야 한다.
where T:Ibase - T는 Ibase 를 구현해야 한다. (여러개의 인터페이스 지정 가능)
where T:U - T는 U의 파생 클래스여야 한다.
ex)
class Test<T> where T:struct
{
private T var;
public T Var
{
get { return var; }
set { var = value; }
}
}
class Program
{
static void Main(string[] args)
{
Test<int> t = new Test<int>();
t.Var = 23;
Console.WriteLine(t.Var);

/*error
Test<string> t = new Test<string>();
t.Var = "hi";
Console.WriteLine(t.Var);
*/
}
}

Exception
: try ~ catch ~ finally 형식이며 throw로 Exception을 던짐.
 크게 Exception과 이를 상속한 SystemException, ApplicationException이 있다.
 
SystemException
IndexOutOfRangeException, DivideByZeroException, FormatException, NullReferenceException,
InvaildCastException, OutOfMemoryException, StackOverflowException, OverflowException

포인터 사용하기
1. 프로젝트 properties > Build > General 에서 "Allow unsafe code" 를 체크 한다.
2. 포인터를 쓰는 곳 마다 unsafe{} 블록을 사용한다.
3. 포인터 사용방법은 C와 동일하다.
fixed 키워드
: 참조 타입에 대한 포인터 사용시 반드시 사용.
(fixed 블록 내에서의 포인터가 유효하도록 보장)
        int[] arr = { 1, 2, 4, 8, 16 };
        unsafe
        {
            fixed (int* pi = &arr[0])
            {
                for (int i=0; i<5; i++)
                {
                    Console.WriteLine(pi[i]);
                }
            }
        }
stackallock 키워드
: 스택영역에 메모리 동적 할당. (스택영역에 할당하므로 자동 해제)
        unsafe
        {
            int* pi = stackalloc int[5];
            for (int i=0; i<5; i++)
            {
                pi[i] = i * 2;
                Console.WriteLine(pi[i]);
            }
        }
Nullable (널 가능 타입)
: "System.Nullable<T> 변수명;" 로 사용하나 축약하여 "?" 기호 사용
ex) bool? isTrue; //boolean값과 null 값을 갖을 수 있는 변수
널 가능타입 사용시 변수는 다음 두가지 property를 갖는다.
HasVAlue : 변수 값이 존재하면 true, null 이면 false
Value : 실제 값이며 null 일 경우 InvalidOperationException 발생.
ex)
        int? a = null;
        if (!a.HasValue) //if (a == null) 과 동일
            Console.WriteLine("a = null");

        int b = a ?? 2; //a가 null이면 2, null이 아니면 a 를 리턴
        Console.WriteLine(b);


Attribute
: 컴파일러에게 코드에 대한 추가 정보 제공
expression)
[어트리뷰트(인수)]
클래스, 메서드, 프로퍼티, 인수 둥..
Conditaional
TTT 의 define 여부에 따라 XXXX() 함수의 컴파일 여부 결정
조건을 만족하지 않을 경우 함수를 호출하는 코드까지 컴파일러에 의해 제거된다.
조건을 두개 이상 적을 경우 OR 조건으로 판별된다. ([Conditional("TTT"),Conditional("YYY")])
ex) 
#define TTT
using System.Diagnostics;
..
[Conditional("TTT")]
public void XXXX() {..}
Obsolete
: deprecated를 의미함. 인수로 컴파일시 출력할 메세지를 지정.
ex) [Obsolete("deprecated됨")]

DllImport
: DLL의 함수 사용시 사용.
ex)
using System.Runtime.InteropServices;

class Program
{
[DllImport("User32.dll")]
public static extern int MessageBox(int hParent, string Message, string Caption, int Type);

[DllImport("Kernel32.dll")]
public static extern uint WinExec(string Path, uint nCmdShow);

static void Main(string[] args)
{
MessageBox(0, "테스트", "warning", 0);
WinExec("notepad.exe", 1);
}
}

Custom Attribute (어트리뷰터 사용자 정의)
: reflect 를 이용해 정보를 가져올 수 있음
Attribute 클래스를 상속하여 클래스 생성하여 정의
ex)
//Attribute의 속성 지정
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited=false)]
class TestAttribute : Attribute
{
string writer;
string createTime;
public TestAttribute(string name) { writer=name; createTime="none";}
public string CreateTime
{
get { return createTime; }
set { createTime = value; }
}
}
class Program
{
//정의한 어트리뷰트 클래스 이름이 "Attribute"로 끝날경우 "Attribute"는 생략 가능
[Test("김", CreateTime = "오늘")]
public static void test() {Console.WriteLine("hi");}

static void Main(string[] args)
{
test();
}
}


Implicitly Typed Local Variable(암묵적 타입)
var 를 사용하여 컴파일러가 자동으로 적절한 타입을 찾는다. (javascript 처럼)
ex) var i = 3;
Initializer (초기자)
class Test
{
public int i;
public int j;
}
class Test2
{
public Test tt;
}
..
Test t = new Test{i=1, j=2};
Test2 t2 = new Test2{tt = new Test{i=1, j=2}}
var anonyVAr = new {a="hi", b="bye"}; //읽기 전용

Extension Method (확장 메소드)
: 클래스를 수정하거나 상속하지 않고 메소드를 추가하는 효과를 낼 수 있다.
public class Test
{
public int num;
public Test(int i) { num = i; }
public int Add(int i) { return num + i; }
}

public static class ExtentTest //클래스 이름은 의미 없음
{
public static int Mul(this Test cls, int i) { return cls.num * i;} //this Test cls 인자
}
..
Test test = new Test(2);
Console.WriteLine(test.Add(1));
Console.WriteLine(test.Mul(2));
Lambda Expression (람다 표현식)
: 익명 메소드의 기능 확장 판으로 간결한 코드 작성 가능
(인수 타입 생략, 표현식 사용, 표현식 트리로 변환 가능)
delegate int dMethod(int i);
class Program
{
static void Main(string[] args)
{
dMethod m = i => i + 1;
//dMethod m = delegate(int i) { return i + 1; };  와 동일
Console.WriteLine(m(2));
}
}

LINQ(Language INtegrated Query) - 쿼리 표현식 (.Net 3.5 이상)
: 언어 독립적인 쿼리 문 지원
LINQ to Object, DataSet, SQL, Entities, XML

expression)
from [where|orderby|let] [select|group]
where : from n in arr where (n%2==0)&&(n%3==0) select n;
orderby : from n in arr where (n%2==0)&&(n%3==0) orderby n descending select n;
let : from n in arr let x=(n%2) let y=(n%3) where (x == 0)&&(y==0) orderby n descending select n;
(변수 임시 저장)
groupby : from n in arr group n by n.XXX;
into : from n in arr group n by n.XXX into gn where gn.ZZZ=="A" orderby gn.YYY select gn;
(groupby 혹은 join 쿼리에 임시 식별자)
subquery: from n in arr where n == (from n2 in arr orderby n2 descending select n2).Max() select n;
join : from n1 in arr join n2 in arr on n1 equals n2 select n1;

ex1)
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
IEnumerable<int> Query = from n in arr where (n % 3 == 0) select n;
foreach (int i in Query)
Console.WriteLine(i);
}
}

ex2)
using System;
using System.Linq;
using System.IO;
class Program
{
static void Main(string[] args)
{
var Dirs = from f in Directory.GetDirectories("c:\\") select f; //디렉토리 목록 획득
Console.WriteLine("Dirs count : " + Dirs.Count());

var Filter = Dirs.Except(from m in Dirs where m == @"c:\WINDOWS" select m);   //윈도우 폴더 제외
Console.WriteLine("Filter count : " + Filter.Count());
foreach (var f in Filter)
Console.WriteLine("\t" + f);
}
}

ex3)
using System;
using System.Linq;
using System.Xml.Linq;

class Test
{
public int a, b;
public Test(int a, int b) { this.a = a; this.b = b;}
}
class Program
{
static void Main(string[] args)
{
Test[] test = { new Test(1, 11), new Test(2, 22) };
var Query = new XElement("root", from p in test select new XElement("Test", new XElement("a", p.a), new XElement("b", p.b)));
Console.WriteLine(Query);
}
}
/* 실행 결과 */
<root>
 <Test>
<a>1</a>
<b>11</b>
 </Test>
 <Test>
<a>2</a>
<b>22</b>
 </Test>
</root>

DLL 제작
1. DLL 프로젝트 생성 : Class Library 
2. 코드 작성 : 공개할 클래스를 public으로 정의
DLL 사용
1. Proeject > Add Reference.. > Browse 탭에서 사용할 dll 파일 선택
(선택한 dll이 실행파일 폴더로 복사됨)
2. 코드 작성

Thread
Thread 생성시 별도로 Start() 실행시 수행된다.
Thread 생성 함수
public Thread(ThreadStart start [,int maxStackSize])
public Thread(ParameterizedThreadStart start [,int maxStackSize])
Thread 생성 함수 인자(delegate)
public delegate void ThreadStart()
public delegate void ParameterizedThreadStart(Object obj)
Thread 멤버 함수
Start(), Suspend(), Resume(), Sleep(), Abort(), Join()
Thread 멤버 변수
Name : thread 이름. 최초 한번 지정 가능
IsAlive : 실행중인 경우 true
IsBackground: Background 스레드인 경우 true로 지정하며 Thread 종료를 대기하지 않고 즉시 종료됨
Priority : 스레드 우선순위(ThreadPriority의 Highest, AboveNormal, Normal, BelowNormal, Lowest로 지정)
ThreadState : 상세한 스레드 현재 상태 조회
CurrentThread: 실행중인 스레드의 프로퍼티. 자기 자신의 Thread 참조를 얻을 수 있음

ex)
using System.Threading;
class Test
{
static void ThreadProc()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
Thread.Sleep(500);
}
}
static void ThreadProc(Object obj)
{
for (int i = 0; i < (int)obj; i++)
{
Console.WriteLine(i);
Thread.Sleep(500);
}
}

static void Main()
{
Thread t1 = new Thread(new ThreadStart(ThreadProc));
t1.Start();
t1.IsBackground = true;

Thread t2 = new Thread(new ParameterizedThreadStart(ThreadProc));
t2.Start(10);
t2.IsBackground = true;
t1.Join();
t2.Join();
}
}

 
Process
AppDomain 을 통해 프로세스간 안전성, 보안, 버전관리 등을 보장 받는다.
ex)
using System;
using System.Diagnostics;
using System.Threading;

class Test
{
static void Main()
{
//프로세스 실행
Process proc = Process.Start("notepad.exe");
Thread.Sleep(1000);
proc.Kill();

//현재 프로세스
Process[] procs = Process.GetProcesses();
foreach (Process p in procs)
{
Console.WriteLine("id:{0,5}, proc={1}", p.Id, p.ProcessName);
if (p.Id != 0)  //System Idle Process 제외
{
//프로세스의 스레드 목록
ProcessThreadCollection ths = p.Threads;
foreach (ProcessThread th in ths)
Console.WriteLine("\tid={0}, priority={1}", th.Id, th.PriorityLevel);

//프로세스에서 사용하는 모듈 목록
ProcessModuleCollection modules = p.Modules;
foreach (ProcessModule m in modules)
Console.WriteLine("\tname={0}", m.ModuleName);
}
}
}
}

Form (폼)
폼 생성 - 직접 생성
1. Empty Project 새성 
2. 프로젝트 properties > Application > Output type 을 Windows Application으로 변경
3. Project > Add Reference.. > .NET 에서 System, System.Drawing, System.Windows.Forms 추가
4. 직접 코딩
using System;
using System.Drawing;
using System.Windows.Forms;


class MDHForm : Form
{
public static void Main()
{
MDHForm form = new MDHForm();
form.Text = "test form";
Application.Run(form);
}
}
폼 생성 - wizard
1. Windows Forms Application 프로젝트 생성


몇몇 class
Form : 윈도우 폼 클래스
Application : 응용 프로그램 자체를 나타내는 클래스
MessageBox : 메세지 박스 클래스
Point : 좌표용 클래스
Size : 사각 영역의 크기를 나타내는 클래스
Rectangle : 사각형을 그리는 클래스
SystemInformation : 현재 시스템 환경 정보를 조회하는 클래스
Timer : 타이머 클래스 혹은 디자이너의 Timer 컴포넌트 사용 가능


이벤트 정의 : 디자인의 properties 창에서 이벤트 함수를 생성하거나 
Form.Paint += new PaintEventHanddler(페인트이벤트함수명) 처럼 정의하여 사용


Application Configuration File (구성 파일)
고급 옵션이나 초기 설정 값을 지정하는 파일 (읽기 전용)
컨트롤의 프로퍼티와 연결가능하여 이를 동적 프로퍼티(dynamic property)라고 한다.

인쇄
PrintDialog : 인쇄 정보를 받는 대화 상자
클립보드
Clipboard : 클립보드 관리 클래스
(SetText, GetText, ContainsText, SetImage, GetImage, ContainsImage, Clear)
(SetDataObject, GetDataObject ..)

Drag & Drop
두 개 이상의 컨트롤의 드래그 & 드롭 효과를 관리
DoDragDrop, DragDropEffects, DragAction










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

숫자 범위 추출 및 확장  (0) 2021.11.03
C# LZ4  (0) 2021.10.20
dictionary 에 action 매핑시 instance method 호출 방법  (0) 2021.10.16
[ASP.NET] .net core 2.2 singleton controller  (0) 2019.08.29
[AppMetrics 3.1.0] ASP.NET Core 2.2 모니터링 with InfluxDB, Grafana  (0) 2019.08.06
[asp.net] asp.net core 2.2 iis 게시  (0) 2019.08.03
C#  (0) 2011.05.15
WPF  (0) 2011.05.08