C
C++은 C를 기반으로 개발되었다. 따라서 일부 예외를 제외하고는 C언어를 부분집합으로 포함한다.
 
■  C++ 언어의 특징
 - C를 기본으로 발전시킨 언어이다.
 - 데이터 추상화를 지원한다.
 - 객체 지향 프로그래밍을 지원한다.
 - 일반화 프로그래밍을 지원한다.

■ C++ 설계 원칙
 - 실행성능을 최대하 높인다.
 - 프로그램의 이식성을 최대한 높인다
 - 쉽게 사용할 수 있게 한다.

■ C++의 장점( C++ better than C)
 C++은 기존 C의 특징을 물려받았을 뿐 아니라 일부 문법은 훨씬 사용하기 편하게 개선되었다.
 - C++에서는 C의 Multi-Line Comment(/* */)외에 추가로 Inline Comment(//)이 제공된다.
 - C++에서는 C와 다르게 함수의 중간에서 변수를 선언하는 것이 가능하다
 - C++에서는 표준입출력을 다루기 위해 3가지 객체를 사용한다.
   . cin   : 표준 입력으로부터 data를 받는다. (ex: cin>>name;)
   . cout : 표준 출력으로 data를 출력한다. (ex: cout<<"hello"<<endl;)
   . cerr : 표준 에러 출력으로 data를 출력한다.
 - C++의 표준 입력출력 객체를 사용하기 위해서는 아래의 헤더파일이 필요하다.
   . iostream.h 또는 iostream
 - 구조체의 인스턴스를 생성할 때 struct 키워드를 생략가능하다.
   
ps. Bjarne Stroutstrup은 C++를 고안하였고, 초기 정의사항을 작성하였다 또한 최초로 C++ 컴파일러를 만들었다.
C#에서 플랫폼 호출 서비스를 이용하면 Manged Code로 작성되지 않은 DLL들을 이용할 수 있다. 이와 같이 PInvoke 서비스를 이용하기 위해서는 다음가 같은 절차대로 코드를 추가한다.

1.  using 지시문을 이용하여 다음과 같이 네임스페이스를 선언
using System.Runtime.InteropServices;

2. class 내에 다음과 같은 형식으로 호출하고자 하는 함수의 원형을 선언한다.
[DllImport("dll경로")]
public static extern Return_Type function(Parameter)

---------------------------------------------------------------------------------

※ 실제 위와 같은 형식으로 WinAPI 프로그램을 할때 하던 방식으로 메시지 처리를 하는 것이 가능하다.

using System.Runtime.InteropServices;

class DLLInvokeTest
{
     private const uint LBUTTONDOWN = 0x00000002;  // WM_LBUTTONDOWN
     private const uint LBUTTONUP = 0x00000004;    // WM_LBUTTONUP

     [DllImport("user32.dll")]
     public static extern int MessageBoxA(int h, string m, string c, int type);
     [DllImport("user32.dll")]
     static extern void mouse_event( uint dwFlags, uint dx, uint dy, uint dwData, int    dwExtraInfo );
     [DllImport("user32.dll")]
     static extern int SetCursorPos(int x,int y);
   
     public static int Main()
     {
           // 메시지박스 호출
           MessageBoxA(null, "Hello World!", "My Message Box", 0);
          
           // 마우스 이벤트 발생
           mouse_event( LBUTTONDOWN, 0, 0, 0, 0 );
           mouse_event( LBUTTONUP, 0, 0, 0, 0 );
          
           return ;
     }

     protected override void WndProc(ref System.Windows.Forms.Message m)
     {
           // m.Msg로 전달되는 메시지를 이곳에서 처리함
      }
}
※ 참고사항
 - dllimport 관련 파라미터에 정보 사이트: http://www.pinvoke.net



C#에서 string을 다음과 같은 방법으로 비교적 쉽게 UTF-8로 인코딩 및 디코딩을 할 수 있다.

        static void Main(string[] args)
        {
            string sample = "테스트";
            Console.WriteLine("<Unicode -> UTF-8 변환하기>");
            Console.WriteLine(" - 문자열 : {0}", sample);

            //인코딩 방식을 지정
            System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
           
            //변환하고자 하는 문자열을 UTF8 방식으로 변환하여 byte 배열로 반환
            byte[] utf8Bytes = utf8.GetBytes(sample);
           
            //UTF-8을 string으로 변한
            string utf8String = "";
            Console.Write(" - Encode: ");
            foreach (byte b in utf8Bytes)
            {
                 utf8String += "%" + String.Format("{0:X}", b);
            }
            Console.WriteLine(utf8String);
 

            // 인코된 문자열 디코딩
            string Unicode = utf8.GetString(utf8Bytes);
            Console.WriteLine(" - Decode: " + Unicode);

// Microsoft.Win32 네임스페이스 사용
using Microsoft.Win32

1. Registry로부터 값 읽기
RegistryKey reg = Registry.LocalMachine;
reg = reg.CreateSubKey(@"SOFTWARE\Microsoft\Internet Explorer", RegistryKeyPermissionCheck.ReadSubTree);
string IEVer = (string)reg.GetValue("Version");
reg.Close();

2. Registry에 값 쓰기
RegistryKey reg = Registry.CurrentUser;
reg = reg.CreateSubKey(@"Software\Microsoft\INternet Explorer\Main", RegistryKeyPermissionCheck.ReadWriteSubTree);
reg.SetValue("Start Page", "www.google.co.kr");
현재 실행파일 경로는 다음과 같이 구할 수 있다.

// 실행파일의 Full Path 구하기
string curPath = Application.ExecutablePath;

int len = curPath.LastIndexOf(@"\");

// 현재 실행파일이 있는 Directory
// Substring(Int32 Index, Int32 Length)은 Index로부터 Length 만큼의 문자열 반환
curPath = curPath.Substring(0, len + 1);


출처: http://msdn.microsoft.com/ko-kr/library/cc148994.aspx

1. 다음 예제에서는 파일 및 디렉터리를 복사하는 방법을 보여 줍니다.

// Simple synchronous file copy operations with no user interface.
// To run this sample, first create the following directories and files:
// C:\Users\Public\TestFolder // C:\Users\Public\TestFolder\test.txt // C:\Users\Public\TestFolder\SubDir\test.txt
public class SimpleFileCopy
{ static void Main() { string fileName = "test.txt"; string sourcePath = @"C:\Users\Public\TestFolder"; string targetPath = @"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths. string sourceFile = System.IO.Path.Combine(sourcePath, fileName); string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location: // Create a new target folder, if necessary. if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); }
// To copy a file to another location and // overwrite the destination file if it already exists. System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory. // Get the files in the source folder. (To recursively iterate through // all subfolders under the current directory, see // "How to: Iterate Through a Directory Tree.") // Note: Check for target path was performed previously // in this code example. if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist. foreach (string s in files) { // Use static Path methods to extract only the file name from the path. fileName = System.IO.Path.GetFileName(s); destFile = System.IO.Path.Combine(targetPath, fileName); System.IO.File.Copy(s, destFile, true); } } else { Console.WriteLine("Source path does not exist!"); }
// Keep console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }


2. 다음 예제에서는 파일 및 디렉터리를 이동하는 방법을 보여 줍니다.

// Simple synchronous file move operations with no user interface.
public class SimpleFileMove
{
    static void Main()
    {
        string sourceFile = @"C:\Users\Public\public\test.txt";
        string destinationFile = @"C:\Users\Public\private\test.txt";

// To move a file or folder to a new location: System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine // path strings, use the System.IO.Path class. System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private"); } }


3. 다음 예제에서는 파일 및 디렉터리를 삭제하는 방법을 보여 줍니다.

// Simple synchronous file deletion operations with no user interface.
// To run this sample, create the following files on your drive:
// C:\Users\Public\DeleteTest\test1.txt
// C:\Users\Public\DeleteTest\test2.txt
// C:\Users\Public\DeleteTest\SubDir\test2.txt

public class SimpleFileDelete { static void Main() { // Delete a file by using File class static method... if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt")) { // Use a try block to catch IOExceptions, to // handle the case of the file already being // opened by another process. try { System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); return; } }
// ...or by using FileInfo instance method. System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");
try { fi.Delete(); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); }
// Delete a directory. Must be writable or empty. try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest"); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); }
// Delete a directory and all subdirectories with Directory static method... if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest")) { try { System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true); }
catch (System.IO.IOException e) { Console.WriteLine(e.Message); } }
// ...or with DirectoryInfo instance method. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public");
// Delete this dir and all subdirs. try { di.Delete(true); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } } }

.NET Framework(C#)에서 프로세스 실행하는 방법입니다.

//Process Class를 상요하기 위해서 하기 namespace를 선언
using System.Diagnostics

1. 프로세스 실행하기
Process.Start("explore.exe", "http://www.naver.com")


2. 프로세스 Hide 상태로 실행하기
ProcessStartInfo startInfo = new ProcessStartInfo(
"explore.exe", "http://www.naver.com");

startInfo.WindowStyle = ProcessWindowStyle.Hidden;

Process.Start(startInfo);


3. 지정된 실행동안 프로세스 종료 대기

Process process = Process.Start(startInfo);


// 1000msec동안 프로세스 종료대기
process.WaitForExit(1000);





+ Recent posts