[C#] 2. 언어구조

Posted by seunggwon
2008. 12. 14. 21:12 IT Note/기타언어
명칭
using System;
class IdentifierApp
{
public static void Main()
{
int MyVar = 1, myvar = 2;
int @int = 10, 변수 = 20;
Console.WriteLine("Myvar = " + MyVar + ", myvar = " + myvar);
Console.WriteLine("@int = " + @int + ", 변수 = " + 변수);
}
}
실행결과
Myvar = 1, myvar = 2
@int = 10, 변수 = 20


정수형상수
using System;
class IntegerConstantApp
{
public static void Main()
{
int i = 255, h = 0Xff;
long l = 0XffL;
Console.WriteLine("i = {0}, h = {1}", i, h);
if (h == 1)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
실행결과
i = 255, h = 255
No


실수형 상수

'IT Note > 기타언어' 카테고리의 다른 글

[C#] 1. C#의 개요  (0) 2008.12.13
[MFC] Menu(2)  (0) 2008.11.24
[MFC] Menu(1)  (0) 2008.11.24

[C#] 1. C#의 개요

Posted by seunggwon
2008. 12. 13. 21:39 IT Note/기타언어
콘솔 애플리케이션 
using System;
class HelloWorld
{
public static void Main()
{
Console.WriteLine("Hello World!");
}
}
실행결과 : Hello World!


윈폼 애플리케이션
using System;
using System.Windows.Forms;
class WinFormApp : Form
{
WinFormApp()
{
Text = "Hello World!";
}
public static void Main()
{
Application.Run(new WinFormApp());
}
}
실행결과



자료형
using System;
class PrimitiveTypeApp
{
public static void Main()
{
bool b;
int i = int.MaxValue;
uint j = uint.MaxValue;
double d = double.MaxValue;
b = (i != 0);
Console.WriteLine("boolean b = " + b);
Console.WriteLine("Max value of signed integer = " + i);
Console.WriteLine("Max value of unsigned integer = " + j);
Console.WriteLine("Max value of double = " + d);
}
}
실행결과
boolean b = True
Max value of signed integer = 2147483647
Max value of unsigned integer = 4294967295
Max value of double = 1.79769313486232E+308


스트링
using System;
class StringApp
{
public static void Main()
{
string s = "Hello";
s += " World";
Console.WriteLine(s + "!");
}
}
실행결과 : Hello World!


프로퍼티
using System;
class PropertyClass
{
private int privateValue;
public int PrivateValue
{
get
{
return privateValue;
}
set
{
privateValue = value;
}
}
public void PrintValue()
{
Console.WriteLine("Hidden Value = " + privateValue);
}
}
class PropertyApp
{
public static void Main()
{
int n;
PropertyClass obj = new PropertyClass();
obj.PrivateValue = 100;
obj.PrintValue();
n = obj.PrivateValue;
Console.WriteLine("       Value = " + n);
}
}
실행결과
Hidden Value = 100
              Value = 100



연산자 중복
using System;
class Even
{
int evenNumber;
public Even(int n) // 생성자
{
evenNumber = (n % 2 == 0) ? n : n+1;
}
public static Even operator++(Even e) // ++연산자
{
e.evenNumber += 2; // 다음 짝수
return e;
}
public static Even operator--(Even e)
{
e.evenNumber -= 2;
return e;
}
public void PrintEven()
{
Console.WriteLine("Even Number = " + evenNumber);
}
}
class OperatorOverloadingApp
{
public static void Main()
{
Even e = new Even(4);
e.PrintEven();
++e;
e.PrintEven();
--e;
e.PrintEven();
}
}
실행결과
Even Number = 4
Even Number = 6
Even Number = 4


델리게이트
using System;
delegate void SampleDelegate(); // 델리게이트 정의
class DelegateClass
{
public void DelegateMethod()
{
Console.WriteLine("In the DelegateClass.DelegateMethod...");
}
}
class DelegateApp
{
public static void Main()
{
DelegateClass obj = new DelegateClass();
SampleDelegate sd = new SampleDelegate(obj.DelegateMethod);
sd(); // invoke obj.DelegateMethod() indirectly.
}
}

실행결과 : In the DelegateClass.DelegateMethod...


이벤트
using System;
using System.Windows.Forms;
class EvenApp : Form
{
public EvenApp() // 생성자
{
this.Click += new EventHandler(ClickEvent); // 이벤트 처리기 등록
}
void ClickEvent(object sender, EventArgs e) // 이벤트 처리기 작성
{
MessageBox.Show("Hello world!");
}
public static void Main()
{
Application.Run(new EvenApp());
}
}
실행결과



스레드
using System;
using System.Threading; // 반드시 포함!
class ThreadApp
{
static void ThreadBody() // 스레드 몸체
{
Console.WriteLine("In the thread body...");
}
public static void Main()
{
ThreadStart ts = new ThreadStart(ThreadBody);
Thread t = new Thread(ts);
Console.WriteLine("*** Start of Main");
t.Start();
Console.WriteLine("*** End of Main");
}
}
실행결과
*** Start of Main
*** End of Main
In the thread body...

'IT Note > 기타언어' 카테고리의 다른 글

[C#] 2. 언어구조  (0) 2008.12.14
[MFC] Menu(2)  (0) 2008.11.24
[MFC] Menu(1)  (0) 2008.11.24

[MFC] Menu(2)

Posted by seunggwon
2008. 11. 24. 14:47 IT Note/기타언어

“Picture” 프로그램 수정
1. Doc에 enum 형의 멤버변수 m_Type 추가
 초기치 - 가운데 보기
2. Menu 추가
화면 설정 - 가운데 보기/전체 보기/타일 보기
3. 각 menu 항목에 command handler 추가

4. 타일 보기 구현
OnDraw 수정 
for(int y=0; y <= rect.bottom; y += bm.bmHeight)
   for(int x=0; x <= rect.right; x += bm.bmWidth)
pDC->BitBlt(x,y,bm.bmWidth,bm.bmHeight,&memDC,
                      0,0,SRCCOPY);
5. 전체보기 구현  
OnDraw 수정
pDC->StretchBlt(0,0,rect.right,rect.bottom,&memDC,
             0,0,bm.bmWidth,bm.bmHeight,SRCCOPY);

class CPictureDoc : public CDocument
{
   ……
 public:
        enum type{CENTER,TILE,FULL};
  type m_Type;
};

void CPictureDoc::OnScreenCenter()
{
 if(m_Type != CENTER)
 {
    m_Type=CENTER;
         UpdateAllViews(NULL); 
     }
}

void CPictureDoc::OnScreenFull()
{
 if(m_Type != FULL)
 {
  m_Type=FULL;
       UpdateAllViews(NULL); 
      }
}

void CPictureDoc::OnScreenTile()
{
 if(m_Type != TILE)
 {
  m_Type=TILE;
       UpdateAllViews(NULL); 
     }
}

void CPictureView::OnDraw(CDC* pDC)
{
  CPictureDoc* pDoc = GetDocument();
  ASSERT_VALID(pDoc);
 
       // TODO: add draw code for native data here
       CDC  memDC;   
       CBitmap MyBit,*pOldBit;
  BITMAP  bm;
  MyBit.LoadBitmap(IDB_TOTO);
       MyBit.GetObject(sizeof(BITMAP),&bm);
       memDC.CreateCompatibleDC(pDC);
  pOldBit=memDC.SelectObject(&MyBit);
      CRect rect;
       GetClientRect(rect);

switch(pDoc->m_Type)
   {
        case CPictureDoc::CENTER : 
     {   int x=(rect.right-bm.bmWidth)/2;
             int y=(rect.bottom-bm.bmHeight)/2;
             pDC->BitBlt(x,y,bm.bmWidth,bm.bmHeight,&memDC,0,0,SRCCOPY);
         }
                 break;

case CPictureDoc::TILE : 
         {
    for(int y=0; y <= rect.bottom; y += bm.bmHeight)
       for(int x=0; x <= rect.right; x += bm.bmWidth)
          pDC->BitBlt(x,y,bm.bmWidth,bm.bmHeight,&memDC,0,0,SRCCOPY);
          }
   break;

case CPictureDoc::FULL :
      pDC->StretchBlt(0,0,rect.right,rect.bottom,&memDC,0,0,
                              bm.bmWidth,bm.bmHeight,SRCCOPY);
             break;     
     }
memDC.SelectObject(pOldBit);
}

 

'IT Note > 기타언어' 카테고리의 다른 글

[C#] 1. C#의 개요  (0) 2008.12.13
[MFC] Menu(1)  (0) 2008.11.24
[MFC] Font  (0) 2008.11.24

[MFC] Menu(1)

Posted by seunggwon
2008. 11. 24. 14:45 IT Note/기타언어

“Shape” 프로그램 수정
1. Menu 추가 ( 도형설정 )
  모양 - 사각형/타원
  라인 색상 - Red/Green/Blue
  내부 색상 - Red/Green/Blue
2. 각 항목에 command handler 추가
3. handler 구현
CWnd::Invalidate. CDocument::UpdateAllViews

void CShapeDoc::OnShapeEllipse()
{
  if(m_bRect)
 { 
  m_bRect = FALSE;
      UpdateAllViews(NULL);
 }
}
void CShapeDoc::OnShapeRect()
{
 if(!m_bRect)
 { 
  m_bRect = TRUE;
  UpdateAllViews(NULL);
 }
      }

void CShapeDoc::OnShapeLinecolorBlue()
{
 if(m_LineColor!=RGB(0,0,255))
     {
      m_LineColor = RGB(0,0,255); 
  UpdateAllViews(NULL);
      }
}
void CShapeDoc::OnShapeLinecolorGreen()
{
 if(m_LineColor!=RGB(0,255,0))
     {
      m_LineColor = RGB(0,255,0); 
  UpdateAllViews(NULL);
     }
}

void CShapeDoc::OnShapeLinecolorRed()
{
 if(m_LineColor!=RGB(255,0,0))
     {
  m_LineColor = RGB(255,0,0); 
  UpdateAllViews(NULL);
     }
}

void CShapeDoc::OnShapeRgncolorBlue()
{
 if(m_RgnColor!=RGB(0,0,255))
     {
   m_RgnColor = RGB(0,0,255); 
  UpdateAllViews(NULL);
     }
}
void CShapeDoc::OnShapeRgncolorGreen()
{
 if(m_RgnColor!=RGB(0,255,0))
     {
   m_RgnColor = RGB(0,255,0); 
  UpdateAllViews(NULL);
     }
}

void CShapeDoc::OnShapeRgncolorRed()
{
 if(m_RgnColor!=RGB(255,0,0))
     {
  m_RgnColor = RGB(255,0,0); 
  UpdateAllViews(NULL);
     }
}

 

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Menu(2)  (0) 2008.11.24
[MFC] Font  (0) 2008.11.24
[MFC] Bitmap  (0) 2008.11.24

[MFC] Font

Posted by seunggwon
2008. 11. 24. 14:42 IT Note/기타언어

1. 프로젝트 생성
 MFC exe, Dialog-based, “MyFont”
 2. 리소스 편집
 Default control을 지운다.
 Control 추가
 편집상자 추가 : IDC_TEXT, m_text(CString)
 종료버튼 추가 : IDC_EXIT, OnExit(), OnOK();
 그룹상자

3. 편집 상자로부터의 message 처리
 IDC_TEXT, EN_CHANGE message
OnChangeText
 Invalidate() : 다시 그린다.
Compile & Build
 4. 편집 상자의 문장 화면 표시
 CMyFontDlg의 OnPaint
CPaintDC dc(this);
UpdateData();
dc.SetBkMode(TRANSPARENT);
CFont fnt, *oldfnt;
fnt.CreateFont(25, 0, 0, 0, 400, FALSE, FALSE, 0,
   ANSI_CHARSET, OUT_DEFAULT_PRECIS,
   CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
   DEFAULT_PITCH | FF_SWISS, "Garamond");
oldfnt = dc.SelectObject(&fnt);
dc.TextOut(100, 200, m_text);
dc.SelectObject(oldfnt);
 5. Font 크기 변경
Font 크기를 위한 그룹상자(이름: Size)
그룹상자 안에 Radio Button 4개 추가
 IDC_SZ25, IDC_SZ50, IDC_SZ75, IDC_SZ100
이전의 Radio Button처럼, 첫번째만 Group으로 지정한다.
 [View/Resource Symbols] 확인
 Class Wizard, Member variable
 IDC_SZ25, Value, int, m_size
 Radio Button 초기화 : OnInitDialog
 m_size = 0; UpdateData(FALSE);
OnPaint 코드 변경
fnt.CreateFont(25 + 25*m_size, 0, 0, 0, 400, FALSE,
FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_SWISS, "Garamond");
dc.TextOut(200, 200, m_text);
IDC_SZ**, BN_CLICKED message 처리 : Invalidate();

6. 글자에 그림자 넣기
 그림자 Check box
IDC_SHADOW, “그림자”
 멤버함수 :  BN_CLICKED, OnShadow(), Invalidate(); 호출
 멤버변수 : Value, int, m_bShadow
 TextOut(200, 200, m_text) 대신에,
if ( m_bShadow ) {
 dc.SetTextColor(RGB(255, 0, 0));
 dc.TextOut(200, 120, m_text);
}
dc.SetTextColor(RGB(0, 255, 0));
dc.TextOut(202, 122, m_text);

7. 다른 font 사용
 List Box 추가
IDC_FONTLIST
 LBN_SELCHANGE, OnSelchangeFontList(), Invalidate(); 호출
 Control, CListBox, m_lbFont
 Font List 초기화
OnInitDialog
 m_lbFont.AddString("Arial");
 m_lbFont.AddString("System");
 m_lbFont.AddString("Times New Roman");
 m_lbFont.AddString("Garamond");
 m_lbFont.SelectString(0, "Arial");
OnPaint 수정


 

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Menu(1)  (0) 2008.11.24
[MFC] Bitmap  (0) 2008.11.24
[MFC] 비트맵(Bitmap) 출력  (0) 2008.11.24

[MFC] Bitmap

Posted by seunggwon
2008. 11. 24. 14:40 IT Note/기타언어

1. 프로젝트 생성
 MFC exe, Dialog-Based, “MyBmp”
 2. 리소스 편집
 모든 default control들을 지우고, Dialog Resizing  가능 속성 선택
Menu 삽입 후 menu 항목 추가
 파일(&F) : 종료(&X)  (IDM_EXIT)
 도움말(&H) : ...에 관하여 (IDM_ABOUT)
Dialog box resource와 menu 연결(dialog box 특성)

3. 코드 작성
 복습
(IDM_EXIT, OnExit) (IDM_ABOUT, OnAbout)
 4. 그림을 추가
 그림파일 준비
 리소스 pop-up menu에서 [Insert] 선택
bitmap [Import]
 참고) 파일이 256 컬러 이하의 해상도의 BMP
IDB_BMPSAMP

5. 그림 표시
 CMyBmpDlg의 OnPaint 함수
else 파트에
CPaintDC dc(this);
HBITMAP hBmp = ::LoadBitmap(
  AfxGetInstanceHandle(),
   MAKEINTRESOURCE(IDB_BMPSAMP));
HDC hMemDC = ::CreateCompatibleDC(NULL);
SelectObject(hMemDC, hBmp);
StretchBlt(dc.m_hDC, 0, 0, 460, 257,
  hMemDC, 0, 0, 460, 257, SRCCOPY);
DeleteDC(hMemDC);
DeleteObject(hBmp);
 Compile & Build

6. 그림 크기 변경
CMyBmpDlg에 size member variable 추가
CSize m_size ;
WM_SIZE message handling (OnSize)
Class Wizard : CMyBmpDlg, WM_SIZE
m_size = CSize(cx, cy);
Invalidate();
OnPaint 코드 변경
StretchBlt(dc.m_hDC, 0, 0, m_size.cx, m_size.cy,
   hMemDC, 0, 0, 460, 257, SRCCOPY);

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Font  (0) 2008.11.24
[MFC] 비트맵(Bitmap) 출력  (0) 2008.11.24
[MFC] Shape  (0) 2008.11.24

[MFC] 비트맵(Bitmap) 출력

Posted by seunggwon
2008. 11. 24. 14:36 IT Note/기타언어

Client 영역 가운데에 비트맵 출력
1. 프로젝트 생성 - SDI, “Picture”
2. BMP화일 리소스에 추가
3. OnDraw 구현

CDC  memDC; CBitmap MyBit, *pOldBit;
BITMAP  bm;
MyBit.LoadBitmap(IDB_TOTO);
MyBit.GetObject(sizeof(BITMAP),&bm);
memDC.CreateCompatibleDC(pDC);
pOldBit=memDC.SelectObject(&MyBit);
CRect rect;      GetClientRect(rect);
int x=(rect.right-bm.bmWidth)/2;
int y=(rect.bottom-bm.bmHeight)/2;  
pDC->BitBlt(x,y,bm.bmWidth,bm.bmHeight,&memDC,0,0,SRCCOPY);
memDC.SelectObject(pOldBit);

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Bitmap  (0) 2008.11.24
[MFC] Shape  (0) 2008.11.24
[MFC] OnDraw 동작  (0) 2008.11.24

[MFC] Shape

Posted by seunggwon
2008. 11. 24. 14:32 IT Note/기타언어

크기가 일정한 사각형 또는 타원 하나를 화면에 항상 출력하는  프로그램
왼쪽 마우스 클릭 :  사각형의 중심 위치 바뀜
오른쪽 마우스 클릭 :  사각형 / 타원 모양 바뀜 
MDI, “Shape”
중심 위치의 초기값 : CPoint(100,100)
모양의 초기값  : 사각형  
색상의 초기값 :  내부색 - 빨강, 라인색-파랑
도형  크기의 초기값 : 높이 100, 폭  100
Client 영역에 원하는 색을 배경으로 칠하기
WM_ERASEBKGND
Cbrush 생성, CDC::FillRect 사용

class CShapeDoc : public CDocument
{  
    ……
   public:
    CPoint  m_Center;
 BOOL   m_bRect;
 CSize   m_Size;
              COLORREF m_LineColor;
 COLORREF m_RgnColor;
     ……
};
BOOL CShapeDoc::OnNewDocument( )
{  
    ……
     m_Center = CPoint(100,100);
 m_bRect = TRUE;
     m_Size = CSize(100,100);
 m_LineColor = RGB(0,0,255);
 m_RgnColor = RGB(255,0,0);
    ……
}
void CShapeView::OnDraw(CDC* pDC)
{    
   CShapeDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    // TODO: add draw code for native data here
    CRect   rect;  
    rect.left=pDoc->m_Center.x-pDoc->m_Size.cx/2;
    rect.top=pDoc->m_Center.y-pDoc->m_Size.cy/2;
    rect.right=pDoc->m_Center.x+pDoc->m_Size.cx/2;
    rect.bottom=pDoc->m_Center.y+pDoc->m_Size.cy/2;

    CPen MyPen,*OldPen;
     MyPen.CreatePen(PS_SOLID,2,pDoc->m_LineColor);
     OldPen=pDC->SelectObject(&MyPen);
     CBrush MyBr,*OldBr;
     MyBr.CreateSolidBrush(pDoc->m_RgnColor);
     OldBr=pDC->SelectObject(&MyBr);
     if(pDoc->m_bRect)
 pDC->Rectangle(rect);
     else
 pDC->Ellipse(rect);
   
    pDC->SelectObject(OldPen);
    pDC->SelectObject(OldBr);
}

void CShapeView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
GetDocument()->m_Center = point;
// Invalidate();
GetDocument()->UpdateAllViews(NULL);
CView::OnLButtonDown(nFlags, point);
}

void CShapeView::OnRButtonDown(UINT nFlags, CPoint point)
{
 // TODO: Add your message handler code here and/or call default
 GetDocument()->m_bRect = !GetDocument()->m_bRect;
 //  Invalidate();
     GetDocument()->UpdateAllViews(NULL);
 
 CView::OnRButtonDown(nFlags, point);
}

BOOL CShapeView::OnEraseBkgnd(CDC* pDC)
{
 // TODO: Add your message handler code here and/or call default
 CBrush Br;
 Br.CreateSolidBrush(RGB(0,125,125));
 CRect rect;
 GetClientRect(rect);
     pDC->FillRect(rect,&Br);
     return TRUE;
 //return CView::OnEraseBkgnd(pDC);
}

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] 비트맵(Bitmap) 출력  (0) 2008.11.24
[MFC] OnDraw 동작  (0) 2008.11.24
[MFC] Graphic 출력  (0) 2008.11.24

[MFC] OnDraw 동작

Posted by seunggwon
2008. 11. 24. 14:29 IT Note/기타언어

1. Project 생성 - MDI로 생성
2. Document class 에 CPoint 형의 멤버 m_pt 추가
protected,  초기값 ( x=10, y=10 )
3. m_pt를 access 할 수 있는 interface function 추가
GetPoint, SetPoint
4. WM_LBUTTONDOWN 의 handler 추가 (View)
m_pt에 현재 마우스 위치를 setting
CClientDC 생성, 이 위치에 푸른 점 출력
CDC::SetPixel
5. OnDraw 구현
m_pt의 위치에 붉은 점 출력
6. Build 후 실행
New Window 메뉴 : 하나의 Doc에 2개의 Views로 보기
왼쪽 마우스 클릭,  resize 등에 의한 결과 비교  

class CShapeDoc : public CDocument
{    ……
     protected:    CPoint    m_pt;
     public :         void       SetPoint(CPoint  pt);
                        CPoint   GetPoint();
      ……
};
BOOL CShapeDoc::OnNewDocument()
{    ……
      m_pt = CPoint(10,10);
     ……
}

void CShapeDoc::SetPoint(CPoint pt)
{
         m_pt=pt;
}
CPoint CShapeDoc::GetPoint()
{
        return m_pt;
}

void CShapeView::OnLButtonDown(UINT nFlags, CPoint point)
{
 // TODO: Add your message handler code here and/or call default
 CClientDC dc(this);
 GetDocument()->SetPoint(point);
 dc.SetPixel(point.x,point.y,RGB(0,0,255));

 CView::OnLButtonDown(nFlags, point);
}
void CShapeView::OnDraw(CDC* pDC)
{
 CShapeDoc* pDoc = GetDocument();
 ASSERT_VALID(pDoc);
  
          // TODO: add draw code for native data here
       CPoint pt = pDoc->GetPoint();
 pDC->SetPixel(pt.x,pt.y,RGB(255,0,0));
}

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Shape  (0) 2008.11.24
[MFC] Graphic 출력  (0) 2008.11.24
[MFC] Text 출력  (0) 2008.11.07

[MFC] Graphic 출력

Posted by seunggwon
2008. 11. 24. 14:26 IT Note/기타언어

 왼쪽 마우스 클릭 시,  View에 꽉 찬 타원 그리기 
1. View에서 WM_LBUTTONDOWN의 handler 추가
2. CClientDC 생성, CDC::Ellipse를 이용하여 타원 출력
현재 client 영역 좌표 
CWnd::GetClientRect
빨간색 라인, 파란색으로 내부가 칠해진 타원 그리기
CPen, CBrush 생성, 대체, 반환


void  CMyView::OnLButtonDown(UINT nFlags, CPoint point)
{
   CClientDC dc(this);
   CRect rect;
   GetClientRect(rect);
   
   CPen MyPen,*OldPen;
   MyPen.CreatePen(PS_SOLID,2,RGB(255,0,0));
   OldPen=dc.SelectObject(&MyPen);
 
   CBrush MyBr,*OldBr;    

   MyBr.CreateHatchBrush(HS_DIAGCROSS,RGB(0,0,255));
   OldBr=dc.SelectObject(&MyBr);
 
   dc.Ellipse(rect);
    
   dc.SelectObject(OldPen);
   dc.SelectObject(OldBr);
 
   CView::OnLButtonDown(nFlags, point);
}

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] OnDraw 동작  (0) 2008.11.24
[MFC] Text 출력  (0) 2008.11.07
[MFC] Keyboard Message 처리  (0) 2008.10.30

[MFC] Text 출력

Posted by seunggwon
2008. 11. 7. 00:51 IT Note/기타언어

현재 마우스가 클릭된 위치에 텍스트 출력
1. String table 에 새로운 string 추가
IDS_RMC_POSITION, “Mouse Button Click at:”
2. Document 에 CString 타입의 member variable 추가 ,
    CDocument::OnNewDocument에서 string을 가져온다
CString::LoadString function을 이용함
3. View에서 WM_RBUTTONDOWN의 handler 추가
4. CClientDC 생성, CDC::TextOut를 이용하여 text 출력 
5. WM_RBUTTONUP의 handler 추가
6. CClientDC 생성, CDC::DrawText를 이용하여 text 출력



void CMyView::OnRButtonDown(UINT nFlags, CPoint point)
{
 CClientDC dc(this);
 dc.SetTextColor(RGB(255,0,0));
 dc.TextOut(point.x, point.y, GetDocument()->m_MouseStr);

 CView::OnRButtonDown(nFlags, point);
}

void CMyView::OnRButtonUp(UINT nFlags, CPoint point)
{
 CClientDC dc(this);
 dc.SetTextColor(RGB(0,0,255));
 CRect rect(point,CSize(100,100));
 dc.DrawText(GetDocument()->m_MouseStr, rect, DT_LEFT | DT_WORDBREAK);
 CView::OnRButtonUp(nFlags, point);
}

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Graphic 출력  (0) 2008.11.24
[MFC] Keyboard Message 처리  (0) 2008.10.30
[MFC] Mouse Message 처리  (0) 2008.10.30

[MFC] Keyboard Message 처리

Posted by seunggwon
2008. 10. 30. 19:33 IT Note/기타언어

키보드의 방향키(LEFT,RIGHT,UP,DOWN)를 사용하여 마우스 커서의 위치 이동
1. WM_KEYDOWN에 대한 메시지 핸들러
2. 각 방향키에 따라 좌,우,위,아래방향으로 각각 10만큼 이동
3. 마우스 커서 관련 함수 - ::SetCursorPos(), ::GetCursorPos()
4. Shift를 누르면서 방향키를 누르면 더 많이 움직일 수 있게 작성

아래의 소스를 추가한다.

void CMessageView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
 CPoint pt;
 if((::GetKeyState(VK_SHIFT)<0) &&(::GetCursorPos(&pt)))
 {
  switch(nChar)
  {
  case VK_LEFT: pt.x-=100;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_RIGHT: pt.x+=100;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_UP: pt.y-=100;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_DOWN: pt.y+=100;
   ::SetCursorPos(pt.x,pt.y);
   break;
  }
 }
 else if(::GetCursorPos(&pt))
 {
  switch(nChar)
  {
  case VK_LEFT: pt.x-=10;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_RIGHT: pt.x+=10;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_UP: pt.y-=10;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_DOWN: pt.y+=10;
   ::SetCursorPos(pt.x,pt.y);
   break;
  }
 }
 CView::OnKeyDown(nChar, nRepCnt, nFlags);
}

하지만 위의 소스는 길이가 길기 때문에, 효율성과 가독성이 떨어진다. 그래서 아래의 소스로 작성하면 효율성과 가독성이 더 증대된다.

void CMessageView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
 CPoint pt;

 if(::GetCursorPos(&pt)) //else //(::GetCursorPos(&pt))
 {
  switch(nChar)
  {
  case VK_LEFT:
   ((GetKeyState(VK_SHIFT)) < 0) ? pt.x-=100 : pt.x-=10;
   //shift키를 눌렀을 때 첫째 실행, 안눌었을 때 두번째 실행됨
   
   ::SetCursorPos(pt.x, pt.y);
   break;
  case VK_RIGHT:
   ((GetKeyState(VK_SHIFT)) < 0) ? pt.x+=100 : pt.x+=10;
   ::SetCursorPos(pt.x, pt.y);
   break;
  case VK_UP: 
   ((GetKeyState(VK_SHIFT)) < 0) ? pt.y-=100 : pt.y-=10;
   ::SetCursorPos(pt.x,pt.y);
   break;
  case VK_DOWN: 
   ((GetKeyState(VK_SHIFT)) < 0) ? pt.y+=100 : pt.y+=10;
   ::SetCursorPos(pt.x,pt.y);
   break;
  }
 }
 
 CView::OnKeyDown(nChar, nRepCnt, nFlags);
}

실행파일 

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Text 출력  (0) 2008.11.07
[MFC] Mouse Message 처리  (0) 2008.10.30
[MFC] Dialog based Program  (0) 2008.10.23

[MFC] Mouse Message 처리

Posted by seunggwon
2008. 10. 30. 19:29 IT Note/기타언어

오른쪽 마우스를 눌렀을 때, 현재 마우스 위치 출력
1. Single Document (SDI)로 작성
2. WM_RBUTTONDOWN와 WM_LBUTTONDOWN에 대한 메시지 핸들러 추가(class wizard 이용)
3. CWnd::MessageBox를 이용하여, 현재의 마우스 위치를 출력한다.
4. ::wsprintf, CString::Format 사용

아래의 소스를 추가한다.
void CMessageView::OnRButtonDown(UINT nFlags, CPoint point)
{
 char buf[20];
 wsprintf(buf,"X:%4d,Y:%4d",point.x,point.y);
 MessageBox(buf,"마우스 위치",MB_OK|MB_ICONINFORMATION);

 CView::OnRButtonDown(nFlags, point);
}

void CMessageView::OnLButtonDown(UINT nFlags, CPoint point)
{
 CString Str;
 Str.Format("x:%4d,Y:%4d",point.x,point.y);
 MessageBox(Str,"마우스 위치",MB_OK|MB_ICONINFORMATION);

 CView::OnLButtonDown(nFlags, point);
}

출력결과(마우스 오른쪽 버튼과 왼쪽 버튼을 눌렀을 경우)

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Keyboard Message 처리  (0) 2008.10.30
[MFC] Dialog based Program  (0) 2008.10.23
[MFC] MFC 소개  (0) 2008.10.23

[MFC] Dialog based Program

Posted by seunggwon
2008. 10. 23. 23:45 IT Note/기타언어
1. 메뉴에서 [File/New] 수행, MFC AppWizard(exe) 선택, 
프로젝트 이름 : Hello


2. 응용프로그램 종류 - Dialog-based 선택


3. Resource View 선택 - DIALOG 폴더에서 IDD_HELLO3_DIALOG 선택
4. “안녕하세요” 누름 Button 추가, 버튼 ID : IDC_HELLO


5. Class Wizard 수행 - IDC_HELLO에 대해 BN_CLICKED 선택한 후 [Add Function] 수행.
[Edit Code] 수행하여 OnHello 코드 작성 - MessageBox("안녕하세요", "Hello");

void CHello3Dlg::OnHello() 
{
MessageBox("안녕하세요","Hello");
}



6. 출력결과

실행파일 

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Mouse Message 처리  (0) 2008.10.30
[MFC] MFC 소개  (0) 2008.10.23
[MFC] Win32 Application 작성하기  (0) 2008.10.23

[MFC] MFC 소개

Posted by seunggwon
2008. 10. 23. 21:40 IT Note/기타언어
The Application Framework




MFC Programming




주요 생성 클래스 예

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] Dialog based Program  (0) 2008.10.23
[MFC] Win32 Application 작성하기  (0) 2008.10.23
[MFC] 급여 프로그램(C++ 복습)  (0) 2008.09.29

[MFC] Win32 Application 작성하기

Posted by seunggwon
2008. 10. 23. 21:33 IT Note/기타언어
다음을 만족하는 Win32 Application을 작성하시오.

이벤트 <메시지 박스 내용>
- 작업영역에서 마우스 왼쪽을 클릭했을때
<
‘마우스 왼쪽 버튼을 클릭하였습니다.’>
- 작업영역에서 마우스 오른쪽을 클릭했을때
<‘마우스 오른쪽 버튼을 클릭하였습니다
.’>
- 작업영역에서 키보드가 눌렸을 때
<‘키보드가 눌렸습니다
.’>


case WM_LBUTTONDOWN:
MessageBox(hWnd, "마우스 왼쪽 버튼을 클릭하였습니다.", "Hello", MB_OK);
break;
case WM_RBUTTONDOWN:
MessageBox(hWnd, "마우스 오른쪽 버튼을 클릭하였습니다.", "Hello", MB_OK);
        break;
case WM_KEYDOWN:
MessageBox(hWnd, "키보드가 눌렸습니다.", "Hello", MB_OK);
break;
추가함...

출력결과








실행파일 

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] MFC 소개  (0) 2008.10.23
[MFC] 급여 프로그램(C++ 복습)  (0) 2008.09.29
[MFC] 계산기 프로그램(C++ 복습)  (0) 2008.09.29

[MFC] 급여 프로그램(C++ 복습)

Posted by seunggwon
2008. 9. 29. 21:50 IT Note/기타언어
/* main에 ID를 입력해서 100대면 manager, 200번대면 salesman, 300번대면 Temporary while문으로 실행한다. 종료시키는 번호 눌르면 종료 */

#include <iostream.h>
class Employee //베이스 클래스
{
protected:
long BaseSalary;
public:
Employee();
virtual void GetSalary();
};

class Manager:public Employee //파생클래스
{
protected:
long ManagerSalary;
public:
Manager();
void GetSalary();
};

class Salesman:public Employee //파생클래스
{
protected:
long SalesSalary;
public:
Salesman();
void GetSalary();
};

class Temporary:public Employee //파생클래스
{
protected:
long TempSalary;
public:
Temporary();
void GetSalary();
};

void Employee::GetSalary()
{
cout<<"사원기본급="<<BaseSalary<<endl;
}
void Manager::GetSalary()
{
cout<<"사원기본급+직급수당="<<(BaseSalary+ManagerSalary)<<endl;
}
void Temporary::GetSalary()
{
cout<<"사원기본급+계약수당="<<(BaseSalary+TempSalary)<<endl;
}
void Salesman::GetSalary()
{
cout<<"사원기본급+영업수당="<<(BaseSalary+SalesSalary)<<endl;
}
Employee::Employee() { BaseSalary=500000; }
Manager::Manager() { ManagerSalary=300000; }
Salesman::Salesman() { SalesSalary=200000; }
Temporary::Temporary() { TempSalary=100000; }

void main()
{
int ID_num; //ID번호
Employee E,*ptrE;
Manager M;
Salesman S;
Temporary T;

while(1)
{
cout<<"================================"<<endl;
cout<<"ID번호를 입력하세요."<<endl;
cout<<"(종료할려면 0을 입력하세요.)"<<endl;
cin>>ID_num;
if(ID_num<0)
{
cout<<"ID번호를 잘못 입력했습니다."<<endl;
}
else if(ID_num==0)
{
cout<<"종료합니다."<<endl;
break;
}
else if(ID_num<100)
{
ptrE=&E;
ptrE->GetSalary();
}
else if(ID_num<200)
{
ptrE=&M;
ptrE->GetSalary();
}
else if(ID_num<300)
{
ptrE=&S;
ptrE->GetSalary();
}
else if(ID_num<400)
{
ptrE=&T;
ptrE->GetSalary();
}
else
{
cout<<"ID번호를 잘못 입력했습니다."<<endl;
}
cout<<"================================"<<endl;
cout<<" "<<endl;
}
}
실행결과

'IT Note > 기타언어' 카테고리의 다른 글

[MFC] MFC 소개  (0) 2008.10.23
[MFC] Win32 Application 작성하기  (0) 2008.10.23
[MFC] 계산기 프로그램(C++ 복습)  (0) 2008.09.29

[MFC] 계산기 프로그램(C++ 복습)

Posted by seunggwon
2008. 9. 29. 21:44 IT Note/기타언어
/* 두 수를 입력하여 +, -, *, /을 구하는 프로그램을 클래스를 이용하여 작성하시오. 단, 연산자 선택은 메뉴를 제공하시오. */

#include <iostream.h>
#include <stdlib.h>
class Cal //계산기 클래스
{
public:
double Val1, Val2; //입력하는 두 값
void Menu(); //입력하고 계산
private:
void Add() { cout<<"="<<Val1+Val2<<endl; } //덧셈
void Sub() { cout<<"="<<Val1-Val2<<endl; } //뺄셈
void Mul() { cout<<"="<<Val1*Val2<<endl; } //곱셈
void Div() { cout<<"="<<Val1/Val2<<endl; } //나눗셈
void False() { cout<<"연산자가 잘못 입력되었습니다."<<endl; }
};

void Cal::Menu()
{
char option; //연산자
while(1)
{
cout<<"=============계산기 프로그램============="<<endl;
cout<<"숫자 연산자 숫자 순으로 입력하세요."<<endl;
cout<<"종료하려면 연산자 부분에 0을 입력하세요."<<endl;
cout<<"========================================="<<endl;
cin>>Val1;
cin>>option>>Val2;
switch(option)
{
case '+': Add(); break;
case '-': Sub(); break;
case '*': Mul(); break;
case '/': Div(); break;
case '0': cout<<"종료합니다."<<endl; exit(0); //연산자가 0을 입력했을 때
default: False();
}
}
}
void main()
{
Cal c;
c.Menu();
}

실행결과


'IT Note > 기타언어' 카테고리의 다른 글

[MFC] MFC 소개  (0) 2008.10.23
[MFC] Win32 Application 작성하기  (0) 2008.10.23
[MFC] 급여 프로그램(C++ 복습)  (0) 2008.09.29