GetClientRect : 클라이언트 영역을 구함


GetWindowRect : 화면전체에서윈도우전체영역을구함


ScreenToClient : 스크린 영역,좌표를 클라이언트 영역, 좌표로 전환함


ClientToScreen : ScreenToClient와 반대로 작동함


GetCursorPos : 화면전체에서마우스커서좌표를얻음


SetCursorPos : 마우스 좌표를 설정함


MoveWindow : 윈도우 크기와 좌표를 조정


SetWindowPos : 윈도우 크기,좌표와 부수적인 것도 설정

'NativeCode > mfc' 카테고리의 다른 글

배경 그림 넣기  (0) 2010.03.18
부모윈도우 호출  (0) 2010.03.18
컨트롤러 투명화 & 색 변화 시키기  (0) 2010.03.18
CStringArray  (0) 2010.03.18
SendMessage 종류  (0) 2010.03.18

CStatic 및 컨트롤러에 배경 투명화시키기



BEGIN_MESSAGE_MAP(CRCS_Client_ProDlg, CDialog)
 //{{AFX_MSG_MAP(CRCS_Client_ProDlg)

 ON_WM_CTLCOLOR() // 컨트롤러에 색 입힐 때 호출됨.
                                 // OnDraw 호출시기와 비슷함.

 //}}AFX_MSG_MAP
END_MESSAGE_MAP()

:
:


HBRUSH CDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
 HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

 pDC->SetBkMode(OPAQUE);

 switch(nCtlColor)
 {
  case CTLCOLOR_STATIC:
  pDC->SetBkColor(RGB(209,210,212));
  pDC->SetTextColor(RGB(0,0,0));
  hbr = (HBRUSH)GetStockObject(NULL_BRUSH);
  break;
 }

 return hbr;
}




// 부가적으로 기능을 더 추가하고 싶다면..


#define  BG_COLOR RGB(234,235,235)
#define STATIC_CLASS_T("Static") 
#define BUTTON_CLASS_T("Button")

:
:

HBRUSH CDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
 HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
 
 if(nCtlColor == CTLCOLOR_STATIC) //Static Text가 그려질 때..
 {
  TCHAR lpszClassName [256]; 
  
  ::GetClassName(pWnd->GetSafeHwnd(), lpszClassName, 255); 
  CString strClass = lpszClassName; 
  
  if (strClass == STATIC_CLASS) 
  { 
   pDC->SetBkMode(TRANSPARENT);  
   return(HBRUSH) ::GetStockObject(HOLLOW_BRUSH); 
  } 
  
  if (strClass == BUTTON_CLASS) //Radio Button의 텍스트가 그려질 때..
  { 
   pDC->SetBkColor(BG_COLOR); //group box
  } 
  return(HBRUSH) ::GetStockObject(HOLLOW_BRUSH); //(NULL_BRUSH = HOLLOW_BRUSH)

 }

 return hbr;
}



*** 참고사항 ***



 CTLCOLOR_BTN

 Button control이 그려질 때, 윈도 95에서는 변경 불가

 CTLCOLOR_DLG

 대화상자가 그려질 때

 CTLCOLOR_EDIT

 Edit Box가 그려질 때

 CTLCOLOR_LISTBOX 

 List Box가 그려질 때

 CTLCOLOR_MSGBOX

 메지시 박스가 그려질 때

 CTLCOLOR_SCROLLBAR

 Scroll Bar가 그려질 때

 CTLCOLOR_STATIC

 Static Text가 그려질 때


'NativeCode > mfc' 카테고리의 다른 글

부모윈도우 호출  (0) 2010.03.18
좌표, 영역 관련 함수  (0) 2010.03.18
CStringArray  (0) 2010.03.18
SendMessage 종류  (0) 2010.03.18
SendMessage  (0) 2010.03.18

int nNicCount = m_CsArrayAdapterName->GetCount();

char *data = ( LPSTR )( LPCTSTR )const_cast< CString &>( m_CsArrayAdapterName->GetAt( i ) );

'NativeCode > mfc' 카테고리의 다른 글

좌표, 영역 관련 함수  (0) 2010.03.18
컨트롤러 투명화 & 색 변화 시키기  (0) 2010.03.18
SendMessage 종류  (0) 2010.03.18
SendMessage  (0) 2010.03.18
WM_COPYDATA  (0) 2010.03.18

SendNotifyMessage 동일한 스레드에서 생성된 윈도우에게 메시지를 보낼 때는 동기식이지만 다른 스레드의 윈도우에게 보낼때는 PostMessage와 같이 비동기식이다.

SendMessageCallback 비동기식으로 작동하며 서버가 메시지 처리가 끝나거나 함수가 실패하였을 때 다섯 번째 인자에 설정된 콜백함수 실행

PostMessage 특정 메시지를 메시지 큐에 넣고 바로 리턴한다. 비동기식식

'NativeCode > mfc' 카테고리의 다른 글

컨트롤러 투명화 & 색 변화 시키기  (0) 2010.03.18
CStringArray  (0) 2010.03.18
SendMessage  (0) 2010.03.18
WM_COPYDATA  (0) 2010.03.18
Message Map  (0) 2010.03.18

받는 쪽

#define WM_MESSGAE WM_USER + 1

LRESULT OnRequestFromClient( WPARAM wParam, LPARAM lParam );

ON_MESSAGE( WM_MESSAGE, OnRequestFromClient)


보내는 쪽

HWND hWnd = ::FindWindow( NULL, "Process Name" );

::SendMessage( hWnd, WM_MESSAGE, 0, 0 );

'NativeCode > mfc' 카테고리의 다른 글

CStringArray  (0) 2010.03.18
SendMessage 종류  (0) 2010.03.18
WM_COPYDATA  (0) 2010.03.18
Message Map  (0) 2010.03.18
MFC Exception  (0) 2010.03.18

받는 쪽

strcut INFO

{

char data[ 100];

}

#define WM_MESSAGE WM_USER + 1

afx_msg bool OnCopyData( CWnd* pWnd, COPYDATASTRUCT *pCopyDataStruct );

ON_WM_COPYDATA()


bool OnCopyData( CWnd *pWnd, COPYDATASTRUCT *pCopyDataStruct )

{

INFO a;


switch( pCopyDataStruct->dwData )

{

case WM_MESSAGE :

memcpy( &a, pCopyDataStruct->lpData);

break;

}


return CDialog::OnCopyData(pWnd, pCopyDataStruct);

}


보내는 쪽

HWND hWnd = ::FindWindow( NULL, "Process Name" );

INFO a;

strcpy( a.data, "Aaaaaaaaaaa" );


COPYDATASTRUCT b;

b.dwData = WM_MESSAGE ;

b.cbData = sizeof( INFO );

b.lpData = &a;


::SendMessage( hWnd, WM_COPYDATA, ( WPARAM )m_hWnd, ( LPARAM )&b );

'NativeCode > mfc' 카테고리의 다른 글

SendMessage 종류  (0) 2010.03.18
SendMessage  (0) 2010.03.18
Message Map  (0) 2010.03.18
MFC Exception  (0) 2010.03.18
MFC Exception 클래스 확장하기  (0) 2010.03.18

메시지 맵 함수

  • http://blog.naver.com/pengooni?Redirect=Log&logNo=100014819687

    웹사이트에 대한 설명을 적습니다.
  • MFC의 메시지 맵 함수  
       
       
    WM_COMMAND 메시지에 대한 핸들러  
       
    맵 엔트리 함수 속성
    ON_COMMAND(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_COMMAND_EX(<id>, <memberFxn>) afx_msg BOOL memberFxn(UNIT);
    ON_COMMAND_EX_RANGE(<id>,
    <idLast>, <memberFxn>)
    afx_msg BOOL memberFxn(UNIT);
    ON_COMMAND_RANGE(<id>, <idLast>,
    <memberFxn>)
    afx_msg void memberFxn(UNIT);
    ON_UPDATE_COMMAND_UI(<id>,
    <memberFxn>)
    afx_msg void memberFxn(CCmdUI*);
    ON_UPDATE_COMMAND_UI_RANGE(<id>,
    <idLast>, <memberFxn>)
    afx_msg void memberFxn(CCmdUI*);
    ON_UPDATE_COMMAND_UI_REFLECT
    (<memberFxn>)
    afx_msg void memberFxn(CCmdUI*);
       
       
    차일드 윈도우 통보 메시지에 대한 핸들러  
       
    맵 엔트리 함수 속성
    일반 컨트롤 통보 코드  
    ON_CONTROL(<wNotifyCode>, <id>,
    <memberFxn>)
    afx_msg void memberFxn();
    ON_CONTROL_RANGE(<wNotifyCode>,
    <id>, <idLast>, <memberFxn>)
    afx_msg void memberFxn(UNIT);
    ON_CONTROL_REFLECT(<wNotifyCode>) afx_msg void memberFxn();
    ON_CONTROL_REFLECT_EX
    (<wNotifyCode>, <memberFxn>)
    afx_msg void memberFxn(NMHDR*,
    LRESULT*);
    ON_NOTIFY(<wNotifyCode>, <id>,
    <memberFxn>)
    afx_msg BOOL memberFxn(UNIT NMHDR*,
    LRESULT*);
    ON_NOTIFY_EX(<wNotifyCode>, <id>,
    <memberFxn>)
    afx_msg BOOL memberFxn(UNIT NMHDR*,
    LRESULT*);
    ON_NOTIFY_EX_RANGE(<wNotifyCode>,
    <id>, <idLast>, <memberFxn>)
    afx_msg void memberFxn(UNIT NMHDR*,
    LRESULT*);
    ON_NOTIFY_REFLECT(<wNotifyCode>,
    <memberFxn>)
    afx_msg void memberFxn(NMHDR*,
    LRESULT*);
    ON_NOTIFY_REFLECT_EX(<wNotifyCode>,
    <memberFxn>)
    afx_msg BOOL memberFxn(NMHDR*,
    LRESULT*);
       
    사용자 버튼 통보 코드  
    ON_BN_CLICKED(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_BN_DOUBLECLICKED(<id>,
    <memberFxn>)
    afx_msg void memberFxn();
    ON_BN_KILLFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_BN_SETFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
       
    콤보 박스 통보 코드  
    ON_CBN_CLOSEUP(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_DBLCLK(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_DROPDOWN(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_EDITCHANGE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_EDITUPDATE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_ERRSPACE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_KILLFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_SELCHANGE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_SELENDCANCEL(<id>,
    <memberFxn>)
    afx_msg void memberFxn();
    ON_CBN_SELENDOK(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_CBN_SETFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
       
    체크 리스트 박스 통보 코드  
    ON_CBN_CHKCHANCE(<id>, <memberFxn>) afx_msg void memberFxn();
       
    에디트 컨트롤 통보 코드  
    ON_EN_CHANGE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_ERRSPACE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_HSCROLL(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_KILLFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_MAXTEXT(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_SETFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_UPDATE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_EN_VSCROLL(<id>, <memberFxn>) afx_msg void memberFxn();
       
    리스트 박스 통보 코드  
    ON_LBN_DBLCLK(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_LBN_ERRSPACE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_LBN_KILLFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_LBN_SELCANCEL(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_LBN_SELCHANGE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_LBN_SETFOCUS(<id>, <memberFxn>) afx_msg void memberFxn();
       
    정적 컨트롤 통보 코드  
    ON_STN_CLICKED(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_STN_DBLCLK(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_STN_DISABLE(<id>, <memberFxn>) afx_msg void memberFxn();
    ON_STN_ENABLE(<id>, <memberFxn>) afx_msg void memberFxn();
       
       
    윈도우 통보 메시지에 대한 핸들러  
    ON_WM_ACTIVATE() afx_msg void OnActivate(UINT,
    CWnd*, BOOL);
    ON_WM_ACTIVATEAPP() afx_msg void OnActivateApp(BOOL, HTASK);
    ON_WM_ASKCBFORMATNAME() afx_msg void OnAskCbFormatName
    (UINT, LPTSTR);
    ON_WM_CANCELMODE() afx_msg void OnCancelMode();
    ON_WM_CAPTURECHANGED() afx_msg void OnCaptureChanged(CWnd*);
    ON_WM_CHANGECBCHAIN() afx_msg void OnChangeCbChain
    (HWND, HWND);
    ON_WM_CHAR() afx_msg void OnChar(UINT, UINT, UINT);
    ON_WM_CHARTOITEM() afx_msg int OnChar ToItem(UINT,
    CListBox*, UINT);
    ON_WM_CHARTOITEM_REFLECT() afx_msg int OnCharToItem(UINT, UINT);
    ON_WM_CHILDACTIVTE() afx_msg void OnChildActivate();
    ON_WM_CLOSE() afx_msg void OnClose();
    ON_WM_COMPACTING() afx_msg void OnCompacting(UINT);
    ON_WM_COMPAREITEM() afx_msg int On CompareItem(int,
    LPCOMPAREITEMSTRUCT);
    ON_WM_COMPAREITEMREFLECT() afx_msg int On CompareItem
    (LPCOMPAREITEMSTRUCT-STRUCT);
    ON_WM_CONTEXTMENU() afx_msg void OnContextMenu(CWnd*,
    CPoint);
    ON_WM_COPYDATA() afx_msg BOOL OnCopyData(CWnd*,
    COPYDATASTRUCT*);
    ON_WM_CREATE() afx_msg int OnCreate(LPCREATESTRUCT);
    ON_WM_CTLCOLOR() afx_msg HBRUSH OnCtlColor(CDC*, UINT);
    ON_WM_DEADCHAR() afx_msg void OnDeadChar
    (UINT, UINT, UINT);
    ON_WM_DELETEITEM() afx_msg void OnDeleteItem(int,
    LPDELETEITEMSTRUCT);
    ON_WM_DELETEITEM_REFLECT() afx_msg void DeleteItem
    (LPDELETEITEMSTRUCT);
    ON_WM_DESTROY() afx_msg void OnDestroy();
    ON_WM_DESTROYCLIPBOARD() afx_msg void OnDestroyClipboard(UINT,
    DWORD);
    ON_WM_DEVICECHANGE() afx_msg BOOL OnDeviceChange(UINT,
    DWORD);
    ON_WM DEVMODECHANGE() afx_msg void OnDevModeChange
    (LPTSTR);
    ON_WM_DRAWCLIPBOARD() afx_msg void OnDrawClipboard();
    ON_WM_DRAWITEM() afx_msg void OnDrawItem(int,
    LPDRAWITEMSTRUCT);
    ON_WM_DRAWITEM_REFLECT() afx_msg void DrawItem
    (LPDRAWITEMSTRUCT);
    ON_WM_DROPFILES() afx_msg void OnDropFiles(HDROP);
    ON_WM_ENABLE() afx_msg void OnEnable(BOOL);
    ON_WM_ENDSESSION() afx_msg void OnEndSession(BOOL);
    ON_WM_ENTERIDLE() afx_msg void OnEnterIdle(UINT, CWnd*);
    ON_WM_ENTERMENULOOP() afx_msg void OnEnterMenuLoop(BOOL);
    ON_WM_ERASEBKGND() afx_msg BOOL OnEraseBkgnd(CDC*)
    ON_WM_EXITMENULOOP() afx_msg void OnExitMenuLoop(BOOL);
    ON_WM_FONTCHANGE() afx_msg void OnFontChange();
    ON_WM_GETDLGCODE() afx_msg UINT OnGetDlgCode();
    ON_WM_GETMINMAXINFO() afx_msg void OnGetMinMaxInfo
    (MINMAXINFO*);
    ON_WM_HELPINFO() afx_msg BOOL OnHelpInfo(MELPINFO*);
    ON_WM_HSCROLL() afx_msg void OnHScroll(UINT,
    UINT, CScrollBar*);
    ON_WM_HSCROLL_REFLECT() afx_msg void HScrool(UINT, UINT);
    ON_WM_HSCROLLCLIPBOARD() afx_msg void OnHScrollClipBoard
    (CWnd* UINT, UINT);
    ON_WM_ICONERASEBKGND() afx_msg void OnIconEraseBkgnd(CDC*);
    ON_WM_INITMNU() afx_msg void OnInitMenu(CMenu*);
    ON_WM_INITMENUPOPUP() afx_msg void OnInitMenuPopup
    (CMenu* UINT, BOOL);
    ON_WM_KEYDOWN() afx_msg void OnKeyDown(UINT, UINT, UINT);
    ON_WM_KEYUP() afx_msg void OnKeyUp(UINT, UINT, UINT);
    ON_WM_KILLFOCUS() afx_msg void OnKillFocus(CWnd*);
    ON_WM_LBUTTONDBLCKLK() afx_msg void OnButtonDblClk(UINT, CPoint);
    ON_WM_LBUTTONDOWN() afx_msg void OnButtonDown(UINT, CPoint);
    ON_WM_LBUTTONUP() afx_msg void OnButtonUp(UINT, CPoint);
    ON_WM_MBUTTONDBLCLK() afx_msg void OnMButtonDblClk(UINT, CPoint);
    ON_WM_MBUTTONDOWN() afx_msg void OnMbuttonDown(UINT, CPoint);
    ON_WM_MBUTTONUP() afx_msg void OnMButtonUp(UINT, CPoint);
    ON_WM_MDIACTIVATE() afx_msg void OnMDIActivate
    (BOOD, CWnd*, CWnd*);
    ON_WM_MEASUREITEM() afx_msg void OnMeasureItem(int,
    LPMEASUREITEMSTRUCT);
    ON_WM_MEASUREITEM_REFLECT() afx_msg void OnMeasureItem
    (LPMEASUREITEMSTRUCT);
    ON_WM_MENUCHAR() afx_msg LRESULT OnMenuChar
    (UINT, UINT, CMenu*);
    ON_WM_MENUSELECT() afx_msg void OnMenuSelect
    (UINT, UINT, HMENU);
    ON_WM_MOUSEACTIVATE() afx_msg OnMouseActivate
    (CWnd*, UINT, UINT);
    ON_WM_MOUSEMOVE() afx_msg OnMouseMove(UINT, Cpoint);
    ON_WM_MOUSEWHELL() afx_msg BOOL OnMouseWhell
    (UINT, short, CPoint);
    ON_WM_MOVE() afx_msg OnMove(int, int);
    ON_WM_MOVING() afx_msg BOOL OnMoveing(UINT, LPRECT);
    ON_WM_NCATIVATE() afx_msg BOOL OnNcActivate(BOOL);
    ON_WM_NCCALCSIZE() afx_msg void OnNcCalcSize(BOOL,
    NCCALCSIZE_PARAMS*);
    ON_WM_NCCREATE() afx_msg BOOL OnNcCreate
    (LPCREATESTRUCT);
    ON_WM_NCDESTROY() afx_msg void OnNcDestroy();
    ON_WM_NCHITTEST() afx_msg UINT OnNcHitTest(CPoint);
    ON_WM_NCLBUTTONDBLCLK() afx_msg void OnNcLButtonDblClk
    (UINT, CPoint);
    ON_WM_NCMBUTTONDOWN() afx_msg void OnNcMButtonDown
    (UINT, CPoint);
    ON_WM_NCMBUTTONUP() afx_msg void OnNcMButtonUp
    (UINT, CPoint);
    ON_WM_NCMOUSEMOVE() afx_msg void OnNcMouseMove
    (UINT, CPoint);
    ON_WM_NCPALNT() afx_msg void OnNPaint();
    ON_WM_NCPBUTTONBLCLK() afx_msg void OnNcRButtonDblClk
    (UINT, CPoint);
    ON_WM_NCRBUTTONDOWN() afx_msg void OnNcRButtonDown
    (UINT, CPoint);
    ON_WM_NCRBUTTONUP() afx_msg void OnNcRButtonUp(UINT, CPoint);
    ON_WM_PAINT() afx_msg void OnPaint();
    ON_WM_PAINTCLIPBOARD() afx_msg void OnPaintClipboard
    (CWnd* HGLOBAL);
    ON_WM_PALETTECHANGED() afx_msg void OnPaletteChanged(CWnd*);
    ON_WM_PALETTEISCHANGING() afx_msg void OnPaletteChanging(CWnd*);
    ON_WM_PARENTNOTIFY() afx_msg void OnParentNotify
    (UNIT, LPARAM);
    ON_WM_PARENTNOTIFY_REFLECT() afx_msg void ParentNotify(UNIT, LPARAM);
    ON_WM_QUERYDRAGICON() afx_msg HCURSOR OnQueryDragIcon();
    ON_WM_QUERYENDSESSION() afx_msg BOOL OnQueryEndSession();
    ON_WM_QUERYNEWPALETTE() afx_msg BOOL OnQueryNewPalette();
    ON_WM_QUERYOPEN() afx_msg BOOL OnQueryOpen();
    ON_WM_RBUTTONDBLCLK() afx_msg void OnRButtonDblclk(UNIT, CPoint);
    ON_WM_RBUTTONDOWN() afx_msg void OnRButtonDown(UNIT, CPoint);
    ON_WM_RBUTTONUP() afx_msg void OnRButtonUp(UINT, CPoint);
    ON_WM_RENDERALLFORMATS() afx_msg void OnRenderAllFormats();
    ON_WM_RENDERFORMATS() afx_msg void OnRenderFormats(UNIT);
    ON_WM_SETCURSOR() afx_msg BOOL OnSetCursor
    (CWnd*, UNIT, UNIT);
    ON_WM_SETFOCUS() afx_msg void OnSetFocus(CWnd*);
    ON_WM_SETTINGCHANGE() afx_msg void OnSettingChange
    (UNIT, LPCTSTR);
    ON_WM_SHOWWINDOW() afx_msg void OnShowWindow(BOOL, UNIT);
    ON_WM_SIZE() afx_msg void OnSize(UNIT, int, int);
    ON_WM_SIZECLIPBOARD() afx_msg void OnSizeClipboard
    (CWnd*, HGLOBAL);
    ON_WM_SIZING() afx_msg void OnSizing(UNIT, LPRECT);
    ON_WM_SPOOLERSTATUS() afx_msg void OnSpoolerStatus(UNIT, UNIT);
    ON_WM_STYLECHANGED() afx_msg void OnStyleChanged(int,
    LPSTYLESRTRUCT);
    ON_WM_STYLECHANGING() afx_msg void OnStyleChanging(int,
    LPSTYLESRTRUCT);
    ON_WM_SYSCHAR() afx_msg void OnSysChar(UNIT, UNIT, UNIT);
    ON_WM_SYSCOLORCHANGE() afx_msg void OnSysColorChange();
    ON_WM_SYSCOMMAND() afx_msg void OnSysCommand
    (UNIT, LPARAM);
    ON_WM_SYSDEADCHAR() afx_msg void OnSysDeadChar
    (UNIT, UNIT, UNIT);
    ON_WM_SYSKEYDOWN() afx_msg void OnSysKeyDown
    (UNIT, UNIT, UNIT);
    ON_WM_SYSKEYUP() afx_msg void OnSysKeyUp(UNIT, UNIT, UNIT);
    ON_WM_TCARD() afx_msg void OnTCard(UNIT, DWORD);
    ON_WM_TIMECHANGE() afx_msg void OnTimeChange();
    ON_WM_TIMER() afx_msg void OnTimer(UNIT);
    ON_WM_VKEYTOITEM() afx_msg void OnVKeyToItem
    (UNIT, CListBox*, UNIT);
    ON_WM_VKEYTOITEM_REFLECT() afx_msg int VKeyToItem(UNIT, UNIT);
    ON_WM_VSCROLL() afx_msg void OnVScroll
    (UNIT, UNIT, CSrollBar*);
    ON_WM_VSCROLL_REFLECT() afx_msg void VScroll(UNIT, UNIT, CScrollBar*);
    ON_WM_VSCROLLCLIPBOARD() afx_msg void OnVScrollClipboard
    (CWnd*, UNIT, UNIT);
    ON_WM_WINDOWPOSCHANGED() afx_msg void OnWindowPosChanged
    (WINDOWPOS*);
    ON_WM_WINDOWPOSCHANGING() afx_msg void OnWindowPosChanging
    (WINDOWPOS*);
    ON_WM_WININICHANGE() afx_msg void OnWinIniChange(LPCTSTR);
       
       
    사용자 정의 메시지에 대한 핸들러  
       
    ON_MESSAGE(<message>, <memberFxn>) afx_msg LRESULT memberFxn(WPARAM,
    LPARAM);
    ON_REGISTERED_MESSAGE
    (<nMessageVariable>, <memberFxn>)
    afx_msg LRESULT memberFxn
    (WPARAM, LPARAM);
    ON_REGISTERED_THREAD_MESSAGE
    (<nMessageVariable>, <memberFxn>)
    afx_msg void memberFxn(WPARAM,
    LPARAM);
    ON_THREAD_MESSAGE(<nMessage>,
    <memberFxn>)
    afx_msg void memberFxn(WPARAM,
    LPARAM);

'NativeCode > mfc' 카테고리의 다른 글

SendMessage  (0) 2010.03.18
WM_COPYDATA  (0) 2010.03.18
MFC Exception  (0) 2010.03.18
MFC Exception 클래스 확장하기  (0) 2010.03.18
TrackPopup  (0) 2010.03.18

클래스명

내용

CMemoryException

메모리부족시에발생하는예외처리클래스

CFileException

파일입출력시발생하는예외처리클래스

CArchiveException

직렬화처리시발생하는예외를정의한다.

CNotSupportedException

지원되지않는기능을요구할경우에발생하는예외처리클래스

CResourceException

리소스할당시발생하는예외처리클래스

COleException

OLE 관련클래스에서발생하는예외처리클래스

CDBException

ODBC 관련클래스에서발생하는예외처리클래스

COleDispatchException

OLE 자동화수행시발생하는예외처리클래스

CUserException

사용자가정의한예외처리클래스

CInternetException

인터넷관련클래스에서발생하는예외처리클래스

CDaoException

DAO 관련클래스에서발생하는예외처리클래스



MFC 예외발생전역함수



요약

내용

AfxThrowArchiveException

직렬화와관련된예외를발생시킨다.

AfxThrowFileException

파일과관련된예외를발생시킨다.

AfxThrowMemoryException

메모리와관련된예외를발생시킨다.

AfxThrowNotSupportedException

메모리와관련된예외를발생시킨다.

AfxThrowResourceException

지원되지않는기능사용에관련된예외를발생시킨다.

AfxThrowUserException

사용자정의예외를발생시킨다.

AfxThrowOleDispatchException

OLE 디스패치와관련된예외를발생시킨다.

AfxThrowOleException

OLE관련된예외를발생시킨다.

AfxThrowDaoException

DAO관련된예외를발생시킨다.

AfxThrowDBException

ODBC관련된예외를발생시킨다.

AfxAbort

어플리케이션을중단종료한다.


'NativeCode > mfc' 카테고리의 다른 글

WM_COPYDATA  (0) 2010.03.18
Message Map  (0) 2010.03.18
MFC Exception 클래스 확장하기  (0) 2010.03.18
TrackPopup  (0) 2010.03.18
Registry 값 읽어오기  (0) 2010.03.18

exception 클래스 확장하기


1.요약 

C++ 표준에는 exception이라는 상위 클래스가 있는데, MFC의 CException 과 같은 역할을 한다고 보시면 됩니다. 

기본적은 exception 을 상속받는 클래스로서 bad_alloc, bad_cast, bad_typeid 등이 있는데, 이상하게도 Visual C++에는 bad_alloc 만 구현하지 않았습니다. 

bad_alloc 은 new 가 실패했을때 던져지도록 약속된 Exception 클래스입니다. 

여기서는 간단하기 bad_alloc을 구현해보겠습니다. 


2.본문 

우선 설명할 내용이 많지 않으므로 소스코드를 보여드리겠습니다. 

#include <new.h> 

#include <exception> 

using namespace std; 



class bad_alloc : public exception 

{ 

public: 

    bad_alloc(const __exString& what_arg) : exception(what_arg) {} 

}; 



int NewHandler(size_t size) 

{ 

    throw bad_alloc("Operator new couldn't allocate memory"); 

    return 0; 

} 



int main(int argc, char* argv[]) 

{ 

    _set_new_handler(NewHandler); 

    _set_new_mode(1);  // use NewHandler for malloc as well 

    .... 

}

이전에 보여드렸던 예제와 크게 다른 점은 없습니다. 

프로그램이 시작할 때( 혹은 각 스레드 엔트리의 처음에서) new handler를 설치해야합니다. 

그리고 _set_new_mode(1); 을 호출함으로써 malloc 역시 new 와 같이 동작하다록 만들 수 있습니다.

보너스로 Exception을 잡으실때(catch) 유의하실 점을 몇가지 적어보겠습니다. 

1. Non-MFC C++ exception 이라면 reference 를 사용하시는 게 좋습니다. 

이렇게 말이죠. 

try { 

    throw MyException(); 

} 

catch(MyException& e) 

{ 

}

이유는 간단합니다. 포인터를 사용한다면 객체를 동적으로 생성/소멸 시키는 루틴이 부가적으로 포함되어야 하기 때문에 안좋을테고, 그냥 MyException 을 사용한다면 추가적인 객체가 생성되고 복사생성자/소멸자가 추가적으로 호출될테니 비효율적이겠죠. 

(참고적으로 dangling reference는 걱정하지 않으셔도 됩니다) 


2. MFC exception 이라면 pointer를 사용해서 잡고, 반드시 Delete() 를 호출해주어야 합니다. 

주의할 점으로는 절대 delete 를 사용해서 해제시켜서는 안됩니다. 
exception이 static object인 경우도 있기 때문입니다.


'NativeCode > mfc' 카테고리의 다른 글

Message Map  (0) 2010.03.18
MFC Exception  (0) 2010.03.18
TrackPopup  (0) 2010.03.18
Registry 값 읽어오기  (0) 2010.03.18
Registry 값 쓰기  (0) 2010.03.18

OnInitDialog에서 메뉴 생성


m_Menu = new CMenu;

m_Menu->LoadMenu( IDR_MENU1 );

pContextMenu = m_Menu->GetSubMenu( 0 );


그 후 OnContextMenu 호출


void CDataBackupDlg::OnContextMenu(CWnd* pWnd, CPoint point)

{

// TODO: 여기에 메시지 처리기 코드를 추가합니다.

pContextMenu->TrackPopupMenu( TPM_LEFTALIGN, point.x, point.y, this );

}
Snap1.bmp Snap2.bmp


Snap4.bmp   


Snap7.bmp Snap5.bmp

Snap6.bmp


'NativeCode > mfc' 카테고리의 다른 글

MFC Exception  (0) 2010.03.18
MFC Exception 클래스 확장하기  (0) 2010.03.18
Registry 값 읽어오기  (0) 2010.03.18
Registry 값 쓰기  (0) 2010.03.18
Static Control 일반적 내용  (0) 2010.03.18

데이터 읽기!


DWORD dwType = REG_SZ;

DWORD dwSize = 128;

HKEY hKey;

TCHAR RecentUpdata[128] = { 0, };

TCHAR CurrentUpdata[ 128 ] = { 0, };


LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE , "SOFTWARE\\H7" , 0 , KEY_READ , &hKey);
if( lResult == ERROR_SUCCESS )

{

RegQueryValueEx( hKey, "Current Version", NULL, &dwType, ( LPBYTE )CurrentUpdata, &dwSize );

RegQueryValueEx( hKey, "Recent Version", NULL, &dwType, ( LPBYTE )RecentUpdata, &dwSize );   

}


Snap1.bmp


'NativeCode > mfc' 카테고리의 다른 글

MFC Exception 클래스 확장하기  (0) 2010.03.18
TrackPopup  (0) 2010.03.18
Registry 값 쓰기  (0) 2010.03.18
Static Control 일반적 내용  (0) 2010.03.18
Static Control Font 설정  (0) 2010.03.18

CRegKey RegKey;
RegKey.Create(HKEY_LOCAL_MACHINE , "SOFTWARE\\TestProg"); 
RegKey.SetValue(rInstalledDate , "Date");
RegKey.Close();


#include <atlbase.h>


Snap1.bmp

'NativeCode > mfc' 카테고리의 다른 글

TrackPopup  (0) 2010.03.18
Registry 값 읽어오기  (0) 2010.03.18
Static Control 일반적 내용  (0) 2010.03.18
Static Control Font 설정  (0) 2010.03.18
SystemParametersInfo  (0) 2010.03.18

가장 단순한 컨트롤, CStatic,은 static 텍스트를 보여준다. CStatic은 데이터 멤버를 가지고 있지 않고, 단지, 약간의 멤버 함수만을 갖고 있다. 생성자, Create 함수등이다. 이것은 유저 이벤트에 응답하지 않는다. 단순하기에, 윈도 컨트롤을 배우기 시작하기에 좋다.

이 튜토리얼에서는 어떻게 컨트롤들이 변형되고, 커스터마이징 되는 지를 이해하기 위해서,

CStatic클래스를 살펴볼 것이다. 다음 튜토리얼에서는 CButton과, CScrollBar클래스를, 이벤트 핸들링의 이해를 위해 살펴볼 것이다. 모든 컨트롤과, 클래스를 이해한다면, 완전한 어플리케이션을 만들 준비가 된 것이다. The Basics

MFC의

CStatic클 래스는 static 텍스트 메시지들을 유저에게 보여준다. 이 메시지들은 정보만을 전달할 수 있다.(예로, 에러 메시지 다이얼로그의 텍스트), 또는 다른 컨트롤들을 구별하게 하는 조그마한 레이블 같은 것으로 이용될 수 있다. 윈도 어플리케이션의 파일 열기 다이얼로그를 열어보면, 여섯 개의 텍스트 레이블을 볼 수 있을 것이다. 다섯 개의 레이블은 리스트와, 텍스트 영역, 그리고, 체크 박스등을 나타내고, 변하지 않는 것들이다. 여섯 번째의 레이블은 현재의 디렉토리를 보여주고, 현재의 디렉토리가 바뀔 때마다, 변하는 것이다. CStatic

객 체는 몇가지 다른 형태를 갖는다. 레이블의 스타일을 변경하여, 사각형으로 보일 수도 있고, 경계선으로 보일 수도 있고, 아이콘으로 보일 수도 있다. CStatic 클래스의 사각 프레임 형태를 이용하면, 관련있는 컨트롤들과 그렇지 않은 컨트롤들을 그룹으로 분류하여 보여줄 수 있다.

CStatic

객체는 항상 어떤 부모 윈도에 대한 차일드 윈도이다. 전형적으로, 부모 윈도는 어플리케이션이나, 다이얼로그 박스를 위한 메인 윈도이다. 튜토리얼 2에서 얘기한 것 처럼, 두 줄의 코드로, static 컨트롤을 만든다. CStatic *cs;
...
cs =
 new

CStatic();
cs->Create("hello world",
                WS_CHILD|WS_VISIBLE|SS_CENTER,
                CRect(50,80, 150, 150),
this
 );

이 두 줄의 생성 스타일은 MFC로 생성되는 컨트롤들의 전형이다.

CStatic의 인스턴스를 위해, new를 호출하여, 메모리를 확보하고, 클래스의 생성자를 호출한다. 생성자는 클래스에 필요한 초기화를 한다. Create

함수는 윈도 레벨의 컨트롤을 생성하고, 스크린으로 보여준다. Create함수는 다섯 파라미터를 받는다. MFC의 헬프에 적혀있는 것 처럼 말이다. Visual C++의 Help메뉴의 Search옵션을 선택하고, Create를 넣어보라. 리스트에서CStatic::Create를 선택할 수 있다. 양자택일로, CStatic를 서치 박스에 입력해서, 그 오버뷰 페이지의 Members

버튼을 누르는 방법도 있겠다.

대개의 값들은 자신을 설명하고 있다.

lpszText파라미터는 레이블로 보여지는 텍스트를 명시하는 것이다. rect 파라미터는 위치와 사이즈, 텍스트의 모양을 조절한다. 부모 윈도 안에 보여질 때 말이다. 텍스트의 왼쪽 윗편 코너는 rect파라미터의 윈쪽 윗편 코너로 정의된다. 사각형은 rect 파라미터의 넓이와 높이를 통해서 정의된다. pParentWnd파라미터는 CStatic컨트롤의 부모를 가리킨다. 이 컨트롤은 부모 윈도에 나타날 것이고, 컨트롤의 위치는 부모의 클라이언트 영역의 왼쪽 윗편 코너와 관계가 있게 될 것이다.nID

파라미터는 API 함수에서 컨트롤 ID로서 사용되는 정수 값이다. 우리는 다음 튜토리얼에서 이 파라미터의 예제들을 보게 될 것이다. dwStyle

파라미터는 제일 중요한 파라미터이다. 컨트롤의 외형과 동작을 제어한다. 다음 섹션들에서 이 파라미터에 대해 자세하게 적을 것이다.

CStatic Styles

모든 컨트롤은 다양한 디스플레이 스타일을 갖는다. 스타일은,

Create함수에서 넘겨지는 dwStyle파라미터를 이용하여, 생성할 때 정의한다. CStatic컨트롤에서 유효한 상수들은 MFC 헬프에서 찾을 수 있고, (이전 섹션에서 얘기한 CStatic::Create함수를 위한 이 페이지를 찾아라. 그리고, 페이지 상단 근처에 있는 Static Control Styles링크를 클릭하라.) 아래에 대강 적어두었다.


Valid styles for the CStatic class-


Styles inherited from CWnd:


  • WS_CHILD Mandatory for CStatic.


  • WS_VISIBLE The control should be visible to the user.


  • WS_DISABLED The control should reject user events.


  • WS_BORDER The control's text is framed by a border.



Styles native to CStatic:


  • SS_BLACKFRAME The control displays itself as a rectangular border. Color is the same as window frames.


  • SS_BLACKRECT The control displays itself as a filled rectangle. Color is the same as window frames.


  • SS_CENTER The text is center justified.


  • SS_GRAYFRAME The control displays itself as a rectangular border. Color is the same as the desktop.


  • SS_GRAYRECT The control displays itself as a filled rectangle. Color is the same as the desktop.


  • SS_ICON The control displays itself as an icon. The text string is used as the name of the icon in a resource file. The rect parameter controls only positioning.


  • SS_LEFT The text displayed is left justified. Extra text is word-wrapped.


  • SS_LEFTNOWORDWRAP The text is left justified, but extra text is clipped.


  • SS_NOPREFIX "&" characters in the text string indicate accelerator prefixes unless this attribute is used.


  • SS_RIGHT The text displayed is right justified. Extra text is word-wrapped.


  • SS_SIMPLE A single line of text is displayed left justified. Any CTLCOLOR messages must be ignored by the parent.


  • SS_USERITEM User-defined item.


  • SS_WHITEFRAME The control displays itself as a rectangular border. Color is the same as window backgrounds.


  • SS_WHITERECT The control displays itself as a filled rectangle. Color is the same as window backgrounds.



이 상수들은 두 개의 다른 뿌리로부터 왔다. "SS"(Static 스타일)상수는 단지
 CStatic컨트롤에만 적용된다. "WS"(Window 스타일)상수는 모든 윈도에 적용되며, 그러므로, CStatic 이 그 동작을 상속 받은, CWnd객체에서 정의된다. CWnd::Create함수를 MFC 문서에서 찾으면 된다. 위의 네 가지만이 CStatic객체에 적용되는 것들이다.
CStatic객 체는 항상 최소한의 두 가지 스타일 상수를 가질 것이다. WS_CHILD 와 WS_VISIBLE 이 그것이다. 컨트롤은 다른 윈도의 차일드가 아니면, 생성되지 않는다. 그리고, WS_VISIBLE 로 설정되지 않으면, 보이지도 않는다. WS_DIABLED 는 레이블의 이벤트로의 응답을 제어한다. 레이블이 키입력이나, 마우스 클릭과 같은 이벤트에 반응이 없기에, 여분이라 할 수 있다. 다른 스타일 속성들은 선택 사항이며, 레이블의 외형을 제어한다.

CStatic::Create함수로의 스타일 속성들을 조정하여, 스크린에 static 객체를 어떻게 나타낼 지를 결정한다. 다음 섹션에서 다룰, 스타일 속성을 이용하여, CStatic객체의 외형을 조정하는 것을 배우면, 스타일들에 대해 많이 이해할 수 있을 것이다.
CStatic Text Appearance아래에 보여진 코드는

CStatic객체의 동작을 이해하는 데에, 유용하다. 이것은 튜토리얼 2에서 본 것과 비슷하다. 그러나, CStatic객체의 생성 부분을 조금 변화시킨 것이다. 튜토리얼 1의 설명으로 돌아가서, 이 코드를 컴파일 해보라.
//static1.cpp #include <afxwin.h>

// Declare the application class class CTestApp : public CWinApp
{
public: virtual BOOL InitInstance();
};

// Create an instance of the application class 
CTestApp TestApp;


// Declare the main window class class CTestWindow : public CFrameWnd
{
        CStatic* cs;
public: 
        CTestWindow();
};

// The InitInstance function is called
// once when the application first executes
 
BOOL CTestApp::InitInstance()
{
        m_pMainWnd =
 new CTestWindow();
        m_pMainWnd->ShowWindow(m_nCmdShow);
        m_pMainWnd->UpdateWindow();
return TRUE;
}


// The constructor for the window class 
CTestWindow::CTestWindow()
{
        CRect r;
// Create the window itself 
        Create(NULL,
                "CStatic Tests",
                WS_OVERLAPPEDWINDOW,
                CRect(0,0,200,200));
// Get the size of the client rectangl e
        GetClientRect(&r);
        r.InflateRect(-20,-20);
// Create a static label 
        cs =
 new CStatic();
        cs->Create("hello world",
                WS_CHILD|WS_VISIBLE|WS_BORDER|SS_CENTER,
                r,
this );
}
 
라인 수와 함께 아래에 반복된, 윈도 생성자를 위한 함수 안의, 코드이다.

  CTestWindow::CTestWindow()
  {
          CRect r;
// Create the window itself 
1         Create(NULL,
                  "CStatic Tests",
                  WS_OVERLAPPEDWINDOW,
                  CRect(0,0,200,200));
// Get the size of the client rectangl e
2         GetClientRect(&r);
3         r.InflateRect(-20,-20);
// Create a static label 
4         cs =
 new CStatic();
5         cs->Create("hello world",
                  WS_CHILD|WS_VISIBLE|WS_BORDER|SS_CENTER,
                  r,
this );
  }
 
함수는 먼저 라인 1에서 윈도를 위해


CTestWindow::Create함수를 불러낸다. 이것은 CFrameWnd객체를 위한 Create함수이다. CTestWindow는 그 동작을 CFrameWnd로부터 상속받았기 때문이다. 라인 1의 코드는 윈도가 200 X 200 픽셀 사이즈를 가져야 하고, 윈도의 왼쪽 윗편이 스크린의 0,0에 초기 위치를 가져야 한다는 것을 말한다. rectDefault상수는 CRect파라미터를 대신할 수 있다. 원한다면 말이다. 라인 2에서 코드는 파라미터

&r을 넘기는, CTestWindow::GetClientRect를 호출한다. GetClientRect함수는 CWnd클래스로부터 상속된다. (MFC 문서내의 함수를 찾을 때, 사이드 바를 보라.) 이 변수 r CRect형이고, 함수의 초기 부분에서 로컬 변수로 선언되었다. 
이 코드를 이해하려고 할 때, 두 가지 질문이 떠오른다.: 1)


GetClientRect함수가 뭘 하는가? 2) CRect변수는 무엇을 하는가? 문제 1과 시작해보도록 하자.CWnd::GetClientRect함수를 MFC 문서에서 찾을 때, 특정 윈도의 클라이언트 사각형 영역의 사이즈를 포함하는, CRect 구조체를 돌려준다는 것을 발견할 수 있을 것이다. 이 경우에는 &r을 말이다. 이 주소는 CRect의 위치를 가리킨다. CRect형은 MFC에서 정의된 클래스이다. MFC 문서에서 클래스를 찾아보면, 사각형을 조정하기 위한 30개가 넘는 멤버 함수와 연산자를 정의하고 있음을 알 수 있을 것이다. 우리의 경우, 윈도의 중앙에 "Hello World"를 위치시키고자 한다. 그러므로,

GetClientRect를 클라이언트 영역을 얻기 위해 사용한다. 라인 3에서 CRect::InflateRect를 호출한다. 대칭적으로 사각형의 사이즈를 증가시키거나 감소시키는 역할을 하는 함수 말이다.(CRect::DeflateRect도 보라.) 여기 우리는 모든 사이드의 20 픽셀씩을 감소시켰다. 그렇게 하지 않으면, 레이블을 둘러싼 보더가 윈도 프레임으로 혼합되어 버릴 것이다. 그리고, 우리는 그걸 볼 수 없을 것이다.실제 CStatic레이블은 라인 4와 5에서 생성된다. 스타일 속성들은, 레이블로 보여지는 단어들이, 중앙에 위치해야하고, 보더로 감싸져야하게, 기술되어 있다. 보더의 사이즈와 위치는 CRect파라미터 r에 의해서 정의된다. 
스타일 속성을 이래저래 변형시켜서, CStatic 객체의 활용을 이해할 수 있을 것이다. 예로, 아래의 코드는 첫 번째 리스트에서의 CTestWindow 생성자 함수를 교체시킨 것을 포함하고 있다.


CTestWindow::CTestWindow()
{
        CRect r;


// Create the window itself 
        Create(NULL,
                "CStatic Tests",
                WS_OVERLAPPEDWINDOW,
                CRect(0,0,200,200));         


// Get the size of the client rectangle 
        GetClientRect(&r);
        r.InflateRect(-20,-20);
 
 


// Create a static label 
        cs =
 new CStatic();
        cs->Create("Now is the time for all good men to \
                come to the aid of their country",
                WS_CHILD|WS_VISIBLE|WS_BORDER|SS_CENTER,
                r,
this );
} 위의 코드는 이전의 것과, 동일하다. 텍스트 스트링이 좀 길어진 것을 제외하고 말이다. 여기서 볼 수 있듯이, 코드를 실행해보면,


CStatic 객체는 고정된 사각형 영역 내에서 텍스트를 랩하고, 각각의 라인을 중앙에 위치시킨다. 
만약에 고정된 사각형 영역이 모든 라인의 텍스트를 포함하기에 너무 작다면, 텍스트는 유효한 공간에 맞게 필요한 만큼 잘릴 것이다.


CStatic객체의 이런 기능은 사각형 영역의 사이즈를 줄이거나, 스트링의 길이를 늘려서, 확인해 볼 수 있다. 지금까지 우리가 본 모든 코드에서는, SS_CENTER 스타일이 텍스트를 중앙에 위치시키기 위해 사용되었다.

CStatic객 체는 왼쪽, 오른쪽으로의 정렬도 가능하게 한다. 왼쪽으로의 정렬은 SS_CENTER 속성 대신에, SS_LEFT 속성을 사용하면 된다. 오른쪽으로의 정렬은 왼쪽 보다는 오른쪽으로 단어들을 위치시킨다. 그리고, 이것은 SS_RIGHT 속성으로 가능하다. 
다른 텍스트 속성도 유효하다. 워드 랩 기능을 해제하고, 종종, 컨트롤들을 설명하는 간단한 레이블로 사용된다. SS_LEFTNOWORDWRAP 스타일은 왼쪽 정렬을 시키고, 랩핑을 없앤다.

Rectangular Display Modes for CStatic
CStatic객 체는 두 개의 사각형 디스플레이 모드를 지원한다.: 속이 차있는 사각형과, 프레임 말이다. 주로 이 두 가지 스타일을 윈도 내에서 다른 컨트롤들을 그룹화하는데 사용할 것이다. 예를 들어, 몇몇의 연관이 있는 에디터 영역을 모아, 윈도에 검은 사각형 프레임을 넣을 것이다. 이런 사각형을 만들 때, 6가지 스타일을 선택할 수 있다.: SS_BLACKFRAME, SS_BLACKRECT, SS_GRAYFRAME, SS_GRAYRECT, SS_WHITEFRAME, SS_WHITERECT 이다. RECT 형은 속이 차있는 사각형이고, 반면에 FRAME은 보더이다. 색상 명은 약간 혼란스러울 수 있다. 예를 들면, SS_WHITERECT는 윈도 배경과 같은 색의 사각형을 보여준다. 이 색상이 기본 값으로 흰색을 사용한다고 해도, 유저는 제어판에서 색을 바꿀 수 있고, 사각형은 실제로 흰색이 아닐 수 있는 것이다. 어떤 머신에서는 말이다. 사각형과 프레임의 속성이 설정될 때,

CStatic의 텍스트 스트링은 무시된다. 빈 스트링이 넘겨지게 된다. 이전 코드에서 몇몇의 이런 스타일을 시도해보고, 결과를 관찰해 보라.
Fonts

CFont객체를 생성하여 CStatic객체의 폰트를 바꿀 수 있다. 그렇게 하는 것은, 어떻게 하나의 MFC 클래스가 다른 것과 함께, 컨트롤들의 동작을 변형해야 하는 몇몇 경우에 있어서, 동작할 수 있는지를 보여준다. MFC의CFont클래스는 특정한 윈도 폰트의 인스턴스 하나를 갖고 있다. 예를 들어, CFont클래스의 하나의 인스턴스는 18 포인트의 Times 폰트를 갖고 있을 것이다. 다른 것이 10 포인트의 Courier 폰트를 가지고 있을 동안 말이다. static 레이블에 의해 사용되는 이 폰트는, CStatic CWnd를 통해서 상속 받은 SetFont함수를 통해서 변형할 수 있다.
아래의 코드는 폰트를 동작하는 데 필요한 코드를 보여준다.
 
CTestWindow::CTestWindow()
{
        CRect r;


// Create the window itself 
        Create(NULL,
                "CStatic Tests",
                WS_OVERLAPPEDWINDOW,
                CRect(0,0,200,200));
// Get the size of the client rectangle 
        GetClientRect(&r);
        r.InflateRect(-20,-20);
// Create a static label 
        cs =
 new CStatic();
        cs->Create("Hello World",
                WS_CHILD|WS_VISIBLE|WS_BORDER|SS_CENTER,
                r,
this );// Create a new 36 point Arial font 
        font =
 new CFont;
        font->CreateFont(36,0,0,0,700,0,0,0,
                ANSI_CHARSET,OUT_DEFAULT_PRECIS,
                CLIP_DEFAULT_PRECIS,
                DEFAULT_QUALITY,
                DEFAULT_PITCH|FF_DONTCARE,
                "arial");
// Cause the label to use the new font 
        cs->SetFont(font);
} 보통 그렇듯이, 위의 코드는, 윈도와


CStatic객체를 생성하는 부분부터 시작한다. 다음, 코드는 CFont형의 객체를 생성한다. 폰트 변수는CTestWindow클래스의 데이터 멤버로서 선언되어야 한다. "CFont *font" 라인과 함께 말이다.CFont::CreateFont함 수는 15개의 파라미터를 가지고 있다. (MFC 헬프를 보라.) 하지만, 대부분의 경우, 단지 세 개만이 중요하다. 예를 들면, 36은 폰트 사이즈 포인트를 의미하고, 700은 폰트의 굵기를 의미한다. (400은 "보통", 700은 "굵게", 1부터 1000까지 사용 가능. FW_NORMAL와 FW_BOLD 상수는 그 같은 의미를 갖고 있다. FW 상수를 API 헬프에서 읽어보아라.) 그리고, "arial"은 사용되는 폰트의 이름이다. 윈도는 다섯 개의 트루 타입 폰트와 함께 유통된다.(Arial, Courier New, Symbol, Times New Roman, Wingdings) 그리고, 어떤 머신이라도 이 폰트들이 존재함을 알 수 있을 것이다. 만약 폰트의 이름을 시스템에서 알 수 없는 것으로 사용을 한다면,CFont클래스는 기본 폰트를 선택할 것이다. 이 튜토리얼에서 이용된 모든 예제에서 말이다.
CFont클래스에 대해서, 좀 더 많은 정보를 원한다면, MFC 문서를 보라. API 온라인 헬프 파일에 좋은 오버뷰가 있다. "Fonts and Text Overview"를 찾아라.

SetFont함수는 CWnd클래스로부터 나온다. 이 시점에서 하나의 의문을 가질 것이다. " CWnd의 어느 함수가CStatic 클래스에 적용되는지 어떻게 알지?" 경험에 의해 배워야 한다. 하루 30분씩, CWnd 안의 모든 함수를 읽어라. 많은 것을 얻을 뿐더러, 컨트롤들을 커스터마이징할 수 있는 많은 함수들을 찾을 수 있을 것이다. 다음 튜토리얼에서는 CWnd클래스의 다른 Set함수들을 볼 예정이다.
Conclusion
이 튜토리얼에서는
 CStatic객체의 많은 활용을 보았다. CWnd로부터 파생된 Set함수들을 남겨놓은 상태이고, 튜토리얼 4에서 얘기할 것이다.

Looking up functions in the Microsoft Documentation
Visual C++ 5.x에서 잘 모르는 함수들을 찾는 것은 매우 쉽다. 모든 MFC,SDK,윈도 API,C.C++ 표준 라이브러리 함수들이 같은 헬프 시스템에 모여있다. 만약 함수가 어디서 정의되었는지, 또는 어떤 구문을 사용하는지, 확신이 서지 않을 때는, 헬프 메뉴의


Search옵션을 이용하라.

Compiling multiple executables
이 튜토리얼은 몇몇의 다른 예제 프로그램을 갖고 있다. 그것들을 컴파일하는데,두 개의 다른 방법이 있다. 첫 번째는 각각의 프로그램들을 각각의 디렉토리에 넣고, 각각을 위한 새 프로젝트를 만드는 것이다. 이 방법으로, 각각의 프로그램을 분리하여 컴파일하고, 동시에, 독립적으로 각각을 실행할 수 있다. 이 방법의 단점은 많은 양의 디스크 공간이 소모된다는 것이다.


두 번째 방법은 이 튜토리얼의 모든 실행 파일을 포함하는 새로운 디렉토리를 생성하는 것이다. 그 디렉토리에서 새로운 프로젝트 하나를 만들어라. 각각의 프로그램을 컴파일하기 위해서, 프로젝트를 수정할 수 있고, 그 소스 파일을 수정할 수 있다. 프로젝트를 재빌드할 때, 새로운 실행 파일은, 당신이 선택한 소스 파일을 반영할 것이다. 이 방법이 디스크 공간 낭비를 줄일 수 있고, 대개 추천하는 방법이다.

'NativeCode > mfc' 카테고리의 다른 글

Registry 값 읽어오기  (0) 2010.03.18
Registry 값 쓰기  (0) 2010.03.18
Static Control Font 설정  (0) 2010.03.18
SystemParametersInfo  (0) 2010.03.18
Timer Callback  (0) 2010.03.18

CFont font;


font.CreateFont( 36, 0, 0, 0, 700, 0, 0, 0,
        ANSI_CHARSET,OUT_DEFAULT_PRECIS,
        CLIP_DEFAULT_PRECIS,
        DEFAULT_QUALITY,
        DEFAULT_PITCH|FF_DONTCARE,
        "맑은 고딕" );

    m_StaticTCP.SetFont( &font );

'NativeCode > mfc' 카테고리의 다른 글

Registry 값 쓰기  (0) 2010.03.18
Static Control 일반적 내용  (0) 2010.03.18
SystemParametersInfo  (0) 2010.03.18
Timer Callback  (0) 2010.03.18
Tray(소스 有)  (0) 2010.03.18
SystemParametersInfo라는 함수가 있다.

이런저런 윈도우의 설정들을 가져 올수 있게 해주는 건데 화면 우측 하단에 특정 이미지를 출력하고 싶어서 찾아가 발견했다.

CRect rtWnd;
::SystemParametersInfo(SPI_GETWORKAREA,0,&rtWnd,0);

요렿게 쓰면 rtWnd에 실 화면의 크기 정보가 얻어진다. 무슨말이냐면 아래쪽 Tray를 제외한 부분이라는거다.
하지만 이렇게 하면 듀얼이상의 모니터를 사용할 경우 1번 모니터의 정보만 얻어오므로 GetMonitorInfo를 사용해야 한다.

그외에 배경화면을 바꾸는 것으로는 

::SystemParametersInfo(SPI_GETDESKWALLPAPER, 0, path, SPFI_SPIF_UPDATEINIFILE | SPIF_SENDCHANGE); 


가 있다. Vista 이상에서만 jpg가 가능하고 그 외에는 모두 bmp만 인식한다.

반대로 현재의 배경화면을 가져오는 것은 Get을 Set으로 바꾸면 완료.

::SystemParametersInfo(SPI_SETDESKWALLPAPER, MAX_PATH, szPath, 0);

기타 parameter들에 대한 설명은 MSDN에서.

SystemParametersInfo Function


Retrieves or sets the value of one of the system-wide parameters. This function can also update the user profile while setting a parameter.


BOOL WINAPI SystemParametersInfo(
  __in          UINT uiAction,
  __in          UINT uiParam,
  __in_out      PVOID pvParam,
  __in          UINT fWinIni
);

Parameters

uiAction

The system-wide parameter to be retrieved or set. This parameter can be one of the following values. They are organized in tables of related parameters.

The following parameters are new for Windows Vista.

ValueMeaning

SPI_GETAUDIODESCRIPTION

Determines whether audio descriptions are enabled or disabled. The pvParam parameter is a pointer to anAUDIODESCRIPTION structure. Set the cbSizemember of this structure and the uiParam parameter tosizeof(AUDIODESCRIPTION).

While it is possible for users who have visual impairments to hear the audio in video content, there is a lot of action in video that does not have corresponding audio. Specific audio description of what is happening in a video helps these users understand the content better. This flag enables you to determine whether audio descriptions have been enabled and in which language.

SPI_GETCLEARTYPE

TBD

SPI_GETCLIENTAREAANIMATION

Determines whether animations are enabled or disabled. The pvParam parameter must point to aBOOL variable that receives TRUE if animations are disabled, or FALSE otherwise.

Display features such as flashing, blinking, flickering, and moving content can cause seizures in users with photo-sensitive epilepsy. This flag enables you to determine whether such animations have been disabled in the client area.

SPI_GETDISABLEOVERLAPPEDCONTENT

Determines whether overlapped content is enabled or disabled. The pvParam parameter must point to aBOOL variable that receives TRUE if enabled, or FALSE otherwise.

Display features such as background images, textured backgrounds, water marks on documents, alpha-blending, and transparency can reduce the contrast between the foreground and background, making it harder for users with low vision to see objects on the screen. This flag enables you to determine whether such overlapped content has been disabled.

SPI_GETMESSAGEDURATION

Retrieves the time that notification pop-ups should be displayed, in seconds. The pvParam parameter must point to a ULONG that receives the message duration.

Users with visual impairments or cognitive conditions such as ADHD and dyslexia might need a longer time to read the text in notification messages. This flag enables you to retrieve the message duration.

SPI_GETSCREENSAVESECURE

TBD

SPI_GETSPEECHRECOGNITION

Determines whether speech recognition is running. The pvParam parameter must point to a BOOLvariable that receives TRUE if speech recognition is running and FALSE otherwise.

Speech recognition monitors running applications and enables the user to interact with the PC by voice to control menus, buttons, and other UI elements, as well as enables the user to convert their voice into text inside a variety of edit-like controls.

SPI_SETAUDIODESCRIPTION

Turns the audio descriptions feature on or off. ThepvParam parameter is a pointer to anAUDIODESCRIPTION structure.

While it is possible for users who are visually impaired to hear the audio in video content, there is a lot of action in video that does not have corresponding audio. Specific audio description of what is happening in a video helps these users understand the content better. This flag enables you to enable or disable audio descriptions in the languages they are provided in.

SPI_SETCLEARTYPE

TBD

SPI_SETCLIENTAREAANIMATION

Turns client area animations on or off. The pvParamparameter is a BOOL variable. Set pvParam to TRUE to disable animations and other transient effects in the client area, or FALSE to enable them.

Display features such as flashing, blinking, flickering, and moving content can cause seizures in users with photo-sensitive epilepsy. This flag enables you to enable or disable all such animations.

SPI_SETDISABLEOVERLAPPEDCONTENT

Turns overlapped content (such as background images and watermarks) on or off. The pvParamparameter is a BOOL variable. Set pvParam to TRUE to disable overlapped content, or FALSE to enable overlapped content.

Display features such as background images, textured backgrounds, water marks on documents, alpha-blending, and transparency can reduce the contrast between the foreground and background, making it harder for users with low vision to see objects on the screen. This flag enables you to enable or disable all such overlapped content.

SPI_SETMESSAGEDURATION

Sets the time that notification pop-ups should be displayed, in seconds. The pvParam parameter must point to a ULONG that specifies the message duration.

Users with visual impairments or cognitive conditions such as ADHD and dyslexia might need a longer time to read the text in notification messages. This flag enables you to set the message duration.

SPI_SETSCREENSAVESECURE

TBD

SPI_SETSPEECHRECOGNITION

Turns a speech recognition utility on or off. SetpvParam to TRUE to turn on the utility, or FALSE otherwise.

The following are the accessibility parameters.

Accessibility parameterMeaning

SPI_GETACCESSTIMEOUT

Retrieves information about the time-out period associated with the accessibility features. The pvParam parameter must point to an ACCESSTIMEOUT structure that receives the information. Set the cbSize member of this structure and theuiParam parameter to sizeof(ACCESSTIMEOUT).

SPI_GETFILTERKEYS

Retrieves information about the FilterKeys accessibility feature. The pvParam parameter must point to a FILTERKEYSstructure that receives the information. Set the cbSize member of this structure and the uiParam parameter tosizeof(FILTERKEYS).

SPI_GETFOCUSBORDERHEIGHT

Retrieves the height, in pixels, of the top and bottom edges of the focus rectangle drawn with DrawFocusRect. ThepvParam parameter must point to a UINT value.

Windows 2000: This value is not supported until Windows XP.

SPI_GETFOCUSBORDERWIDTH

Retrieves the width, in pixels, of the left and right edges of the focus rectangle drawn with DrawFocusRect. The pvParamparameter must point to a UINT.

Windows 2000: This value is not supported until Windows XP.

SPI_GETHIGHCONTRAST

Retrieves information about the HighContrast accessibility feature. The pvParam parameter must point to aHIGHCONTRAST structure that receives the information. Set the cbSize member of this structure and the uiParamparameter to sizeof(HIGHCONTRAST).

For a general discussion, see Remarks.

SPI_GETMOUSECLICKLOCK

Retrieves the state of the Mouse ClickLock feature. ThepvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE otherwise. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_GETMOUSECLICKLOCKTIME

Retrieves the time delay before the primary mouse button is locked. The pvParam parameter must point to DWORD that receives the time delay, in milliseconds. This is only enabled if SPI_SETMOUSECLICKLOCK is set to TRUE. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_GETMOUSEKEYS

Retrieves information about the MouseKeys accessibility feature. The pvParam parameter must point to a MOUSEKEYSstructure that receives the information. Set the cbSize member of this structure and the uiParam parameter tosizeof(MOUSEKEYS).

SPI_GETMOUSESONAR

Retrieves the state of the Mouse Sonar feature. The pvParamparameter must point to a BOOL variable that receives TRUE if enabled or FALSE otherwise. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_GETMOUSEVANISH

Retrieves the state of the Mouse Vanish feature. The pvParamparameter must point to a BOOL variable that receives TRUE if enabled or FALSE otherwise. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_GETSCREENREADER

Determines whether a screen reviewer utility is running. A screen reviewer utility directs textual information to an output device, such as a speech synthesizer or Braille display. When this flag is set, an application should provide textual information in situations where it would otherwise present the information graphically.

The pvParam parameter is a pointer to a BOOL variable that receives TRUE if a screen reviewer utility is running, or FALSE otherwise.

SPI_GETSERIALKEYS

The user should control this setting through the Control Panel.

Windows Me/98/95: Retrieves information about the SerialKeys accessibility feature. The pvParamparameter must point to a SERIALKEYS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter tosizeof(SERIALKEYS).

SPI_GETSHOWSOUNDS

Determines whether the Show Sounds accessibility flag is on or off. If it is on, the user requires an application to present information visually in situations where it would otherwise present the information only in audible form. The pvParamparameter must point to a BOOL variable that receives TRUE if the feature is on, or FALSE if it is off.

Using this value is equivalent to calling GetSystemMetricswith SM_SHOWSOUNDS. That is the recommended call.

SPI_GETSOUNDSENTRY

Retrieves information about the SoundSentry accessibility feature. The pvParam parameter must point to aSOUNDSENTRY structure that receives the information. Set the cbSize member of this structure and the uiParamparameter to sizeof(SOUNDSENTRY).

SPI_GETSTICKYKEYS

Retrieves information about the StickyKeys accessibility feature. The pvParam parameter must point to aSTICKYKEYS structure that receives the information. Set thecbSize member of this structure and the uiParam parameter tosizeof(STICKYKEYS).

SPI_GETTOGGLEKEYS

Retrieves information about the ToggleKeys accessibility feature. The pvParam parameter must point to aTOGGLEKEYS structure that receives the information. Set thecbSize member of this structure and the uiParam parameter tosizeof(TOGGLEKEYS).

SPI_SETACCESSTIMEOUT

Sets the time-out period associated with the accessibility features. The pvParam parameter must point to anACCESSTIMEOUT structure that contains the new parameters. Set the cbSize member of this structure and theuiParam parameter to sizeof(ACCESSTIMEOUT).

SPI_SETFILTERKEYS

Sets the parameters of the FilterKeys accessibility feature. ThepvParam parameter must point to a FILTERKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter tosizeof(FILTERKEYS).

SPI_SETFOCUSBORDERHEIGHT

Sets the height of the top and bottom edges of the focus rectangle drawn with DrawFocusRect to the value of thepvParam parameter.

Windows 2000: This value is not supported until Windows XP.

SPI_SETFOCUSBORDERWIDTH

Sets the height of the left and right edges of the focus rectangle drawn with DrawFocusRect to the value of the pvParamparameter.

Windows 2000: This value is not supported until Windows XP.

SPI_SETHIGHCONTRAST

Sets the parameters of the HighContrast accessibility feature. The pvParam parameter must point to a HIGHCONTRASTstructure that contains the new parameters. Set the cbSizemember of this structure and the uiParam parameter tosizeof(HIGHCONTRAST).

SPI_SETMOUSECLICKLOCK

Turns the Mouse ClickLock accessibility feature on or off. This feature temporarily locks down the primary mouse button when that button is clicked and held down for the time specified by SPI_SETMOUSECLICKLOCKTIME. The uiParam parameter specifies TRUE for on, or FALSE for off. The default is off. For more information, see Remarks and About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_SETMOUSECLICKLOCKTIME

Adjusts the time delay before the primary mouse button is locked. The uiParam parameter specifies the time delay in milliseconds. For example, specify 1000 for a 1 second delay. The default is 1200. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_SETMOUSEKEYS

Sets the parameters of the MouseKeys accessibility feature. The pvParam parameter must point to a MOUSEKEYSstructure that contains the new parameters. Set the cbSizemember of this structure and the uiParam parameter tosizeof(MOUSEKEYS).

SPI_SETMOUSESONAR

Turns the Sonar accessibility feature on or off. This feature briefly shows several concentric circles around the mouse pointer when the user presses and releases the CTRL key. The pvParam parameter specifies TRUE for on and FALSE for off. The default is off. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_SETMOUSEVANISH

Turns the Vanish feature on or off. This feature hides the mouse pointer when the user types; the pointer reappears when the user moves the mouse. The pvParam parameter specifies TRUE for on and FALSE for off. The default is off. For more information, see About Mouse Input.

Windows 2000: This value is not supported until Windows XP.

SPI_SETSCREENREADER

Determines whether a screen review utility is running. TheuiParam parameter specifies TRUE for on, or FALSE for off.

SPI_SETSERIALKEYS

The user controls this feature through the Control Panel.

Windows Me/98/95: Sets the parameters of theSerialKeys accessibility feature. The pvParamparameter must point to a SERIALKEYS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter tosizeof(SERIALKEYS).

SPI_SETSHOWSOUNDS

Turns the ShowSounds accessibility feature on or off. TheuiParam parameter specifies TRUE for on, or FALSE for off.

SPI_SETSOUNDSENTRY

Sets the parameters of the SoundSentry accessibility feature. The pvParam parameter must point to a SOUNDSENTRYstructure that contains the new parameters. Set the cbSizemember of this structure and the uiParam parameter tosizeof(SOUNDSENTRY).

SPI_SETSTICKYKEYS

Sets the parameters of the StickyKeys accessibility feature. The pvParam parameter must point to a STICKYKEYSstructure that contains the new parameters. Set the cbSizemember of this structure and the uiParam parameter tosizeof(STICKYKEYS).

SPI_SETTOGGLEKEYS

Sets the parameters of the ToggleKeys accessibility feature. The pvParam parameter must point to a TOGGLEKEYSstructure that contains the new parameters. Set the cbSizemember of this structure and the uiParam parameter tosizeof(TOGGLEKEYS).

The following are the desktop parameters.

Desktop parameterMeaning

SPI_GETDESKWALLPAPER

Retrieves the full path of the bitmap file for the desktop wallpaper. The pvParam parameter must point to a buffer to receive the null-terminated path string. Set theuiParam parameter to the size, in characters, of thepvParam buffer. The returned string will not exceed MAX_PATH characters. If there is no desktop wallpaper, the returned string is empty.

SPI_GETDROPSHADOW

Determines whether the drop shadow effect is enabled. The pvParam parameter must point to a BOOL variable that returns TRUE if enabled or FALSE if disabled.

Windows 2000: This value is not supported until Windows XP.

SPI_GETFLATMENU

Determines whether native User menus have flat menu appearance. The pvParam parameter must point to aBOOL variable that returns TRUE if the flat menu appearance is set, or FALSE otherwise.

Windows 2000: This value is not supported until Windows XP.

SPI_GETFONTSMOOTHING

Determines whether the font smoothing feature is enabled. This feature uses font antialiasing to make font curves appear smoother by painting pixels at different gray levels.

The pvParam parameter must point to a BOOL variable that receives TRUE if the feature is enabled, or FALSE if it is not.

SPI_GETFONTSMOOTHINGCONTRAST

Retrieves a contrast value that is used in ClearTypesmoothing. The pvParam parameter must point to aUINT that receives the information. Valid contrast values are from 1000 to 2200. The default value is 1400.

Windows 2000: This value is not supported until Windows XP.

SPI_GETFONTSMOOTHINGORIENTATION

Retrieves the font smoothing orientation. The pvParamparameter must point to a UINT that receives the information. The possible values are FE_FONTSMOOTHINGORIENTATIONBGR (blue-green-red) and FE_FONTSMOOTHINGORIENTATIONRGB (red-green-blue).

Windows XP/2000: This value is not supported until Windows XP SP2.

SPI_GETFONTSMOOTHINGTYPE

Retrieves the type of font smoothing. The pvParamparameter must point to a UINT that receives the information. The possible values are FE_FONTSMOOTHINGSTANDARD and FE_FONTSMOOTHINGCLEARTYPE.

Windows 2000: This value is not supported until Windows XP.

SPI_GETWORKAREA

Retrieves the size of the work area on the primary display monitor. The work area is the portion of the screen not obscured by the system taskbar or by application desktop toolbars. The pvParam parameter must point to a RECT structure that receives the coordinates of the work area, expressed in virtual screen coordinates.

To get the work area of a monitor other than the primary display monitor, call the GetMonitorInfofunction.

SPI_SETCURSORS

Reloads the system cursors. Set the uiParamparameter to zero and the pvParam parameter to NULL

SPI_SETDESKPATTERN

Sets the current desktop pattern by causing Windows to read the Pattern= setting from the WIN.INI file.

SPI_SETDESKWALLPAPER

Sets the desktop wallpaper. The value of the pvParamparameter determines the new wallpaper. To specify a wallpaper bitmap, set pvParam to point to a null-terminated string containing the full path to the bitmap file. Setting pvParam to "" removes the wallpaper. Setting pvParam to SETWALLPAPER_DEFAULT or NULL reverts to the default wallpaper.

Starting with Windows Vista, pvParam can specify a .jpg file.

SPI_SETDROPSHADOW

Enables or disables the drop shadow effect. SetpvParam to TRUE to enable the drop shadow effect or FALSE to disable it. You must also have CS_DROPSHADOW in the window class style.

Windows 2000: This value is not supported until Windows XP.

SPI_SETFLATMENU

Enables or disables flat menu appearance for native User menus. Set pvParam to TRUE to enable flat menu appearance or FALSE to disable it.

When enabled, the menu bar uses COLOR_MENUBAR for the menubar background, COLOR_MENU for the menu-popup background, COLOR_MENUHILIGHT for the fill of the current menu selection, and COLOR_HILIGHT for the outline of the current menu selection. If disabled, menus are drawn using the same metrics and colors as in Windows 2000.

Windows 2000: This value is not supported until Windows XP.

SPI_SETFONTSMOOTHING

Enables or disables the font smoothing feature, which uses font antialiasing to make font curves appear smoother by painting pixels at different gray levels.

To enable the feature, set the uiParam parameter to TRUE. To disable the feature, set uiParam to FALSE.

SPI_SETFONTSMOOTHINGCONTRAST

Sets the contrast value used in ClearType smoothing. The pvParam parameter is the contrast value. Valid contrast values are from 1000 to 2200. The default value is 1400.

SPI_SETFONTSMOOTHINGTYPE must also be set to FE_FONTSMOOTHINGCLEARTYPE.

Windows 2000: This value is not supported until Windows XP.

SPI_SETFONTSMOOTHINGORIENTATION

Sets the font smoothing orientation. The pvParamparameter is either FE_FONTSMOOTHINGORIENTATIONBGR (blue-green-red) or FE_FONTSMOOTHINGORIENTATIONRGB (red-green-blue).

Windows XP/2000: This value is not supported until Windows XP SP2.

SPI_SETFONTSMOOTHINGTYPE

Sets the font smoothing type. The pvParam parameter is either FE_FONTSMOOTHINGSTANDARD, if standard anti-aliasing is used, or FE_FONTSMOOTHINGCLEARTYPE, if ClearType is used. The default is FE_FONTSMOOTHINGSTANDARD.

SPI_SETFONTSMOOTHING must also be set.

Windows 2000: This value is not supported until Windows XP.

SPI_SETWORKAREA

Sets the size of the work area. The work area is the portion of the screen not obscured by the system taskbar or by application desktop toolbars. ThepvParam parameter is a pointer to a RECT structure that specifies the new work area rectangle, expressed in virtual screen coordinates. In a system with multiple display monitors, the function sets the work area of the monitor that contains the specified rectangle.

The following are the icon parameters.

Icon parameterMeaning

SPI_GETICONMETRICS

Retrieves the metrics associated with icons. The pvParamparameter must point to an ICONMETRICS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(ICONMETRICS).

SPI_GETICONTITLELOGFONT

Retrieves the logical font information for the current icon-title font. The uiParam parameter specifies the size of a LOGFONTstructure, and the pvParam parameter must point to theLOGFONT structure to fill in.

SPI_GETICONTITLEWRAP

Determines whether icon-title wrapping is enabled. ThepvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.

SPI_ICONHORIZONTALSPACING

Sets or retrieves the width, in pixels, of an icon cell. The system uses this rectangle to arrange icons in large icon view.

To set this value, set uiParam to the new value and set pvParamto NULL. You cannot set this value to less than SM_CXICON.

To retrieve this value, pvParam must point to an integer that receives the current value.

SPI_ICONVERTICALSPACING

Sets or retrieves the height, in pixels, of an icon cell.

To set this value, set uiParam to the new value and set pvParamto NULL. You cannot set this value to less than SM_CYICON.

To retrieve this value, pvParam must point to an integer that receives the current value.

SPI_SETICONMETRICS

Sets the metrics associated with icons. The pvParam parameter must point to an ICONMETRICS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(ICONMETRICS).

SPI_SETICONS

Reloads the system icons. Set the uiParam parameter to zero and the pvParam parameter to NULL.

SPI_SETICONTITLELOGFONT

Sets the font that is used for icon titles. The uiParam parameter specifies the size of a LOGFONT structure, and the pvParamparameter must point to a LOGFONT structure.

SPI_SETICONTITLEWRAP

Turns icon-title wrapping on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.

The following are the input parameters. They include parameters related to the keyboard, mouse, input language, and the warning beeper.

Input parameterMeaning

SPI_GETBEEP

Determines whether the warning beeper is on.

The pvParam parameter must point to a BOOL variable that receives TRUE if the beeper is on, or FALSE if it is off.

SPI_GETBLOCKSENDINPUTRESETS

Retrieves a BOOL indicating whether an application can reset the screensaver's timer by calling the SendInputfunction to simulate keyboard or mouse input. The pvParamparameter must point to a BOOL variable that receives TRUE if the simulated input will be blocked, or FALSE otherwise.

SPI_GETDEFAULTINPUTLANG

Retrieves the input locale identifier for the system default input language. The pvParam parameter must point to anHKL variable that receives this value. For more information, see Languages, Locales, and Keyboard Layouts.

SPI_GETKEYBOARDCUES

Determines whether menu access keys are always underlined. The pvParam parameter must point to a BOOLvariable that receives TRUE if menu access keys are always underlined, and FALSE if they are underlined only when the menu is activated by the keyboard.

SPI_GETKEYBOARDDELAY

Retrieves the keyboard repeat-delay setting, which is a value in the range from 0 (approximately 250 ms delay) through 3 (approximately 1 second delay). The actual delay associated with each value may vary depending on the hardware. The pvParam parameter must point to an integer variable that receives the setting.

SPI_GETKEYBOARDPREF

Determines whether the user relies on the keyboard instead of the mouse, and wants applications to display keyboard interfaces that would otherwise be hidden. The pvParamparameter must point to a BOOL variable that receives TRUE if the user relies on the keyboard; or FALSE otherwise.

SPI_GETKEYBOARDSPEED

Retrieves the keyboard repeat-speed setting, which is a value in the range from 0 (approximately 2.5 repetitions per second) through 31 (approximately 30 repetitions per second). The actual repeat rates are hardware-dependent and may vary from a linear scale by as much as 20%. ThepvParam parameter must point to a DWORD variable that receives the setting.

SPI_GETMOUSE

Retrieves the two mouse threshold values and the mouse acceleration. The pvParam parameter must point to an array of three integers that receives these values. Seemouse_event for further information.

SPI_GETMOUSEHOVERHEIGHT

Retrieves the height, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. The pvParamparameter must point to a UINT variable that receives the height.

SPI_GETMOUSEHOVERTIME

Retrieves the time, in milliseconds, that the mouse pointer has to stay in the hover rectangle for TrackMouseEvent to generate a WM_MOUSEHOVER message. The pvParamparameter must point to a UINT variable that receives the time.

SPI_GETMOUSEHOVERWIDTH

Retrieves the width, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. The pvParamparameter must point to a UINT variable that receives the width.

SPI_GETMOUSESPEED

Retrieves the current mouse speed. The mouse speed determines how far the pointer will move based on the distance the mouse moves. The pvParam parameter must point to an integer that receives a value which ranges between 1 (slowest) and 20 (fastest). A value of 10 is the default. The value can be set by an end-user using the mouse control panel application or by an application using SPI_SETMOUSESPEED.

SPI_GETMOUSETRAILS

Determines whether the Mouse Trails feature is enabled. This feature improves the visibility of mouse cursor movements by briefly showing a trail of cursors and quickly erasing them.

The pvParam parameter must point to an integer variable that receives a value. If the value is zero or 1, the feature is disabled. If the value is greater than 1, the feature is enabled and the value indicates the number of cursors drawn in the trail. The uiParam parameter is not used.

Windows 2000: This value is not supported until Windows XP.

SPI_GETSNAPTODEFBUTTON

Determines whether the snap-to-default-button feature is enabled. If enabled, the mouse cursor automatically moves to the default button, such as OK or Apply, of a dialog box. The pvParam parameter must point to a BOOL variable that receives TRUE if the feature is on, or FALSE if it is off.

SPI_GETWHEELSCROLLCHARS

Retrieves the number of characters to scroll when the horizontal mouse wheel is moved. The pvParam parameter must point to a UINT variable that receives the number of lines. The default value is 3.

SPI_GETWHEELSCROLLLINES

Retrieves the number of lines to scroll when the vertical mouse wheel is moved. The pvParam parameter must point to a UINT variable that receives the number of lines. The default value is 3.

SPI_SETBEEP

Turns the warning beeper on or off. The uiParam parameter specifies TRUE for on, or FALSE for off.

SPI_SETBLOCKSENDINPUTRESETS

Determines whether an application can reset the screensaver's timer by calling the SendInput function to simulate keyboard or mouse input. The uiParam parameter specifies TRUE if the screensaver will not be deactivated by simulated input, or FALSE if the screensaver will be deactivated by simulated input.

SPI_SETDEFAULTINPUTLANG

Sets the default input language for the system shell and applications. The specified language must be displayable using the current system character set. The pvParamparameter must point to an HKL variable that contains the input locale identifier for the default language. For more information, see Languages, Locales, and Keyboard Layouts.

SPI_SETDOUBLECLICKTIME

Sets the double-click time for the mouse to the value of theuiParam parameter. The double-click time is the maximum number of milliseconds that can occur between the first and second clicks of a double-click. You can also call theSetDoubleClickTime function to set the double-click time. To get the current double-click time, call theGetDoubleClickTime function.

SPI_SETDOUBLECLKHEIGHT

Sets the height of the double-click rectangle to the value of the uiParam parameter.

The double-click rectangle is the rectangle within which the second click of a double-click must fall for it to be registered as a double-click.

To retrieve the height of the double-click rectangle, callGetSystemMetrics with the SM_CYDOUBLECLK flag.

SPI_SETDOUBLECLKWIDTH

Sets the width of the double-click rectangle to the value of the uiParam parameter.

The double-click rectangle is the rectangle within which the second click of a double-click must fall for it to be registered as a double-click.

To retrieve the width of the double-click rectangle, callGetSystemMetrics with the SM_CXDOUBLECLK flag.

SPI_SETKEYBOARDCUES

Sets the underlining of menu access key letters. ThepvParam parameter is a BOOL variable. Set pvParam to TRUE to always underline menu access keys, or FALSE to underline menu access keys only when the menu is activated from the keyboard.

SPI_SETKEYBOARDDELAY

Sets the keyboard repeat-delay setting. The uiParamparameter must specify 0, 1, 2, or 3, where zero sets the shortest delay (approximately 250 ms) and 3 sets the longest delay (approximately 1 second). The actual delay associated with each value may vary depending on the hardware.

SPI_SETKEYBOARDPREF

Sets the keyboard preference. The uiParam parameter specifies TRUE if the user relies on the keyboard instead of the mouse, and wants applications to display keyboard interfaces that would otherwise be hidden; uiParam is FALSE otherwise.

SPI_SETKEYBOARDSPEED

Sets the keyboard repeat-speed setting. The uiParamparameter must specify a value in the range from 0 (approximately 2.5 repetitions per second) through 31 (approximately 30 repetitions per second). The actual repeat rates are hardware-dependent and may vary from a linear scale by as much as 20%. If uiParam is greater than 31, the parameter is set to 31.

SPI_SETLANGTOGGLE

Sets the hot key set for switching between input languages. The uiParam and pvParam parameters are not used. The value sets the shortcut keys in the keyboard property sheets by reading the registry again. The registry must be set before this flag is used. the path in the registry is \HKEY_CURRENT_USER\keyboard layout\toggle. Valid values are "1" = ALT+SHIFT, "2" = CTRL+SHIFT, and "3" = none.

SPI_SETMOUSE

Sets the two mouse threshold values and the mouse acceleration. The pvParam parameter must point to an array of three integers that specifies these values. Seemouse_event for further information.

SPI_SETMOUSEBUTTONSWAP

Swaps or restores the meaning of the left and right mouse buttons. The uiParam parameter specifies TRUE to swap the meanings of the buttons, or FALSE to restore their original meanings.

To retrieve the current setting, call GetSystemMetrics with the SM_SWAPBUTTON flag.

SPI_SETMOUSEHOVERHEIGHT

Sets the height, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. Set the uiParamparameter to the new height.

SPI_SETMOUSEHOVERTIME

Sets the time, in milliseconds, that the mouse pointer has to stay in the hover rectangle for TrackMouseEvent to generate a WM_MOUSEHOVER message. This is used only if you pass HOVER_DEFAULT in the dwHoverTime parameter in the call to TrackMouseEvent. Set the uiParamparameter to the new time.

The time specified should be between USER_TIMER_MAXIMUM and USER_TIMER_MINIMUM. IfuiParam is less than USER_TIMER_MINIMUM, the function will use USER_TIMER_MINIMUM. If uiParam is greater than USER_TIMER_MAXIMUM, the function will be USER_TIMER_MAXIMUM.

Windows Server 2003 and Windows XP: The operating system does not enforce the use of USER_TIMER_MAXIMUM and USER_TIMER_MINIMUM until Windows Server 2003 SP1 and Windows XP SP2.

SPI_SETMOUSEHOVERWIDTH

Sets the width, in pixels, of the rectangle within which the mouse pointer has to stay for TrackMouseEvent to generate a WM_MOUSEHOVER message. Set the uiParamparameter to the new width.

SPI_SETMOUSESPEED

Sets the current mouse speed. The pvParam parameter is an integer between 1 (slowest) and 20 (fastest). A value of 10 is the default. This value is typically set using the mouse control panel application.

SPI_SETMOUSETRAILS

Enables or disables the Mouse Trails feature, which improves the visibility of mouse cursor movements by briefly showing a trail of cursors and quickly erasing them.

To disable the feature, set the uiParam parameter to zero or 1. To enable the feature, set uiParam to a value greater than 1 to indicate the number of cursors drawn in the trail.

Windows 2000: This value is not supported until Windows XP.

SPI_SETSNAPTODEFBUTTON

Enables or disables the snap-to-default-button feature. If enabled, the mouse cursor automatically moves to the default button, such as OK or Apply, of a dialog box. Set the uiParam parameter to TRUE to enable the feature, or FALSE to disable it. Applications should use theShowWindow function when displaying a dialog box so the dialog manager can position the mouse cursor.

SPI_SETWHEELSCROLLCHARS

Sets the number of characters to scroll when the horizontal mouse wheel is moved. The number of characters is set from the uiParam parameter.

SPI_SETWHEELSCROLLLINES

Sets the number of lines to scroll when the vertical mouse wheel is moved. The number of lines is set from theuiParam parameter.

The number of lines is the suggested number of lines to scroll when the mouse wheel is rolled without using modifier keys. If the number is 0, then no scrolling should occur. If the number of lines to scroll is greater than the number of lines viewable, and in particular if it is WHEEL_PAGESCROLL (#defined as UINT_MAX), the scroll operation should be interpreted as clicking once in the page down or page up regions of the scroll bar.

The following are the menu parameters.

Menu parameterMeaning

SPI_GETMENUDROPALIGNMENT

Determines whether pop-up menus are left-aligned or right-aligned, relative to the corresponding menu-bar item. ThepvParam parameter must point to a BOOL variable that receives TRUE if right-aligned, or FALSE otherwise.

SPI_GETMENUFADE

Determines whether menu fade animation is enabled. ThepvParam parameter must point to a BOOL variable that receives TRUE when fade animation is enabled and FALSE when it is disabled. If fade animation is disabled, menus use slide animation. This flag is ignored unless menu animation is enabled, which you can do using the SPI_SETMENUANIMATION flag. For more information, seeAnimateWindow.

SPI_GETMENUSHOWDELAY

Retrieves the time, in milliseconds, that the system waits before displaying a shortcut menu when the mouse cursor is over a submenu item. The pvParam parameter must point to aDWORD variable that receives the time of the delay.

SPI_SETMENUDROPALIGNMENT

Sets the alignment value of pop-up menus. The uiParamparameter specifies TRUE for right alignment, or FALSE for left alignment.

SPI_SETMENUFADE

Enables or disables menu fade animation. Set pvParam to TRUE to enable the menu fade effect or FALSE to disable it. If fade animation is disabled, menus use slide animation. he The menu fade effect is possible only if the system has a color depth of more than 256 colors. This flag is ignored unless SPI_MENUANIMATION is also set. For more information, seeAnimateWindow.

SPI_SETMENUSHOWDELAY

Sets uiParam to the time, in milliseconds, that the system waits before displaying a shortcut menu when the mouse cursor is over a submenu item.

The following are the power parameters.

Power parameterMeaning

SPI_GETLOWPOWERACTIVE

Determines whether the low-power phase of screen saving is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE if disabled. This flag is supported for 32-bit applications only.

SPI_GETLOWPOWERTIMEOUT

Retrieves the time-out value for the low-power phase of screen saving. The pvParam parameter must point to an integer variable that receives the value. This flag is supported for 32-bit applications only.

SPI_GETPOWEROFFACTIVE

Determines whether the power-off phase of screen saving is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE if disabled. This flag is supported for 32-bit applications only.

SPI_GETPOWEROFFTIMEOUT

Retrieves the time-out value for the power-off phase of screen saving. The pvParam parameter must point to an integer variable that receives the value. This flag is supported for 32-bit applications only.

SPI_SETLOWPOWERACTIVE

Activates or deactivates the low-power phase of screen saving. Set uiParam to 1 to activate, or zero to deactivate. The pvParamparameter must be NULL. This flag is supported for 32-bit applications only.

SPI_SETLOWPOWERTIMEOUT

Sets the time-out value, in seconds, for the low-power phase of screen saving. The uiParam parameter specifies the new value. The pvParam parameter must be NULL. This flag is supported for 32-bit applications only.

SPI_SETPOWEROFFACTIVE

Activates or deactivates the power-off phase of screen saving. SetuiParam to 1 to activate, or zero to deactivate. The pvParamparameter must be NULL. This flag is supported for 32-bit applications only.

SPI_SETPOWEROFFTIMEOUT

Sets the time-out value, in seconds, for the power-off phase of screen saving. The uiParam parameter specifies the new value. The pvParam parameter must be NULL. This flag is supported for 32-bit applications only.

The following are the screen saver parameters.

Screen saver parameterMeaning

SPI_GETSCREENSAVEACTIVE

Determines whether screen saving is enabled. The pvParamparameter must point to a BOOL variable that receives TRUE if screen saving is enabled, or FALSE otherwise.

SPI_GETSCREENSAVERRUNNING

Determines whether a screen saver is currently running on the window station of the calling process. The pvParam parameter must point to a BOOL variable that receives TRUE if a screen saver is currently running, or FALSE otherwise. Note that only the interactive window station, WinSta0, can have a screen saver running.

SPI_GETSCREENSAVETIMEOUT

Retrieves the screen saver time-out value, in seconds. ThepvParam parameter must point to an integer variable that receives the value.

SPI_SETSCREENSAVEACTIVE

Sets the state of the screen saver. The uiParam parameter specifies TRUE to activate screen saving, or FALSE to deactivate it.

SPI_SETSCREENSAVETIMEOUT

Sets the screen saver time-out value to the value of theuiParam parameter. This value is the amount of time, in seconds, that the system must be idle before the screen saver activates.

The following are the UI effects. The SPI_SETUIEFFECTS value is used to enable or disable all UI effects at once. This table contains the complete list of UI effect values.

UI effects parameterMeaning

SPI_GETCOMBOBOXANIMATION

Determines whether the slide-open effect for combo boxes is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE for enabled, or FALSE for disabled.

SPI_GETCURSORSHADOW

Determines whether the cursor has a shadow around it. The pvParam parameter must point to a BOOL variable that receives TRUE if the shadow is enabled, FALSE if it is disabled. This effect appears only if the system has a color depth of more than 256 colors.

SPI_GETGRADIENTCAPTIONS

Determines whether the gradient effect for window title bars is enabled. The pvParam parameter must point to aBOOL variable that receives TRUE for enabled, or FALSE for disabled. For more information about the gradient effect, see the GetSysColor function.

SPI_GETHOTTRACKING

Determines whether hot tracking of user-interface elements, such as menu names on menu bars, is enabled. The pvParam parameter must point to a BOOLvariable that receives TRUE for enabled, or FALSE for disabled.

Hot tracking means that when the cursor moves over an item, it is highlighted but not selected. You can query this value to decide whether to use hot tracking in the user interface of your application.

SPI_GETLISTBOXSMOOTHSCROLLING

Determines whether the smooth-scrolling effect for list boxes is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE for enabled, or FALSE for disabled.

SPI_GETMENUANIMATION

Determines whether the menu animation feature is enabled. This master switch must be on to enable menu animation effects. The pvParam parameter must point to aBOOL variable that receives TRUE if animation is enabled and FALSE if it is disabled.

If animation is enabled, SPI_GETMENUFADE indicates whether menus use fade or slide animation.

SPI_GETMENUUNDERLINES

Same as SPI_GETKEYBOARDCUES.

SPI_GETSELECTIONFADE

Determines whether the selection fade effect is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled or FALSE if disabled.

The selection fade effect causes the menu item selected by the user to remain on the screen briefly while fading out after the menu is dismissed.

SPI_GETTOOLTIPANIMATION

Determines whether ToolTip animation is enabled. ThepvParam parameter must point to a BOOL variable that receives TRUE if enabled or FALSE if disabled. If ToolTip animation is enabled, SPI_GETTOOLTIPFADE indicates whether ToolTips use fade or slide animation.

SPI_GETTOOLTIPFADE

If SPI_SETTOOLTIPANIMATION is enabled, SPI_GETTOOLTIPFADE indicates whether ToolTip animation uses a fade effect or a slide effect. ThepvParam parameter must point to a BOOL variable that receives TRUE for fade animation or FALSE for slide animation. For more information on slide and fade effects, see AnimateWindow.

SPI_GETUIEFFECTS

Determines whether UI effects are enabled or disabled. The pvParam parameter must point to a BOOL variable that receives TRUE if all UI effects are enabled, or FALSE if they are disabled.

SPI_SETCOMBOBOXANIMATION

Enables or disables the slide-open effect for combo boxes. Set the pvParam parameter to TRUE to enable the gradient effect, or FALSE to disable it.

SPI_SETCURSORSHADOW

Enables or disables a shadow around the cursor. ThepvParam parameter is a BOOL variable. Set pvParam to TRUE to enable the shadow or FALSE to disable the shadow. This effect appears only if the system has a color depth of more than 256 colors.

SPI_SETGRADIENTCAPTIONS

Enables or disables the gradient effect for window title bars. Set the pvParam parameter to TRUE to enable it, or FALSE to disable it. The gradient effect is possible only if the system has a color depth of more than 256 colors. For more information about the gradient effect, see theGetSysColor function.

SPI_SETHOTTRACKING

Enables or disables hot tracking of user-interface elements such as menu names on menu bars. Set thepvParam parameter to TRUE to enable it, or FALSE to disable it.

Hot-tracking means that when the cursor moves over an item, it is highlighted but not selected.

SPI_SETLISTBOXSMOOTHSCROLLING

Enables or disables the smooth-scrolling effect for list boxes. Set the pvParam parameter to TRUE to enable the smooth-scrolling effect, or FALSE to disable it.

SPI_SETMENUANIMATION

Enables or disables menu animation. This master switch must be on for any menu animation to occur. ThepvParam parameter is a BOOL variable; set pvParam to TRUE to enable animation and FALSE to disable animation.

If animation is enabled, SPI_GETMENUFADE indicates whether menus use fade or slide animation.

SPI_SETMENUUNDERLINES

Same as SPI_SETKEYBOARDCUES.

SPI_SETSELECTIONFADE

Set pvParam to TRUE to enable the selection fade effect or FALSE to disable it.

The selection fade effect causes the menu item selected by the user to remain on the screen briefly while fading out after the menu is dismissed. The selection fade effect is possible only if the system has a color depth of more than 256 colors.

SPI_SETTOOLTIPANIMATION

Set pvParam to TRUE to enable ToolTip animation or FALSE to disable it. If enabled, you can use SPI_SETTOOLTIPFADE to specify fade or slide animation.

SPI_SETTOOLTIPFADE

If the SPI_SETTOOLTIPANIMATION flag is enabled, use SPI_SETTOOLTIPFADE to indicate whether ToolTip animation uses a fade effect or a slide effect. SetpvParam to TRUE for fade animation or FALSE for slide animation. The tooltip fade effect is possible only if the system has a color depth of more than 256 colors. For more information on the slide and fade effects, see theAnimateWindow function.

SPI_SETUIEFFECTS

Enables or disables UI effects. Set the pvParamparameter to TRUE to enable all UI effects or FALSE to disable all UI effects.

The following are the window parameters.

Window parameterMeaning

SPI_GETACTIVEWINDOWTRACKING

Determines whether active window tracking (activating the window the mouse is on) is on or off. The pvParamparameter must point to a BOOL variable that receives TRUE for on, or FALSE for off.

SPI_GETACTIVEWNDTRKZORDER

Determines whether windows activated through active window tracking will be brought to the top. The pvParamparameter must point to a BOOL variable that receives TRUE for on, or FALSE for off.

SPI_GETACTIVEWNDTRKTIMEOUT

Retrieves the active window tracking delay, in milliseconds. The pvParam parameter must point to aDWORD variable that receives the time.

SPI_GETANIMATION

Retrieves the animation effects associated with user actions. The pvParam parameter must point to anANIMATIONINFO structure that receives the information. Set the cbSize member of this structure and the uiParamparameter to sizeof(ANIMATIONINFO).

SPI_GETBORDER

Retrieves the border multiplier factor that determines the width of a window's sizing border. The pvParamparameter must point to an integer variable that receives this value.

SPI_GETCARETWIDTH

Retrieves the caret width in edit controls, in pixels. ThepvParam parameter must point to a DWORD variable that receives this value.

SPI_GETDRAGFULLWINDOWS

Determines whether dragging of full windows is enabled. The pvParam parameter must point to a BOOL variable that receives TRUE if enabled, or FALSE otherwise.

SPI_GETFOREGROUNDFLASHCOUNT

Retrieves the number of times SetForegroundWindowwill flash the taskbar button when rejecting a foreground switch request. The pvParam parameter must point to aDWORD variable that receives the value.

SPI_GETFOREGROUNDLOCKTIMEOUT

Retrieves the amount of time following user input, in milliseconds, during which the system will not allow applications to force themselves into the foreground. ThepvParam parameter must point to a DWORD variable that receives the time.

SPI_GETMINIMIZEDMETRICS

Retrieves the metrics associated with minimized windows. The pvParam parameter must point to aMINIMIZEDMETRICS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(MINIMIZEDMETRICS).

SPI_GETNONCLIENTMETRICS

Retrieves the metrics associated with the nonclient area of nonminimized windows. The pvParam parameter must point to a NONCLIENTMETRICS structure that receives the information. Set the cbSize member of this structure and the uiParam parameter to sizeof(NONCLIENTMETRICS).

SPI_GETSHOWIMEUI

Determines whether the IME status window is visible (on a per-user basis). The pvParam parameter must point to a BOOL variable that receives TRUE if the status window is visible, or FALSE if it is not.

SPI_SETACTIVEWINDOWTRACKING

Sets active window tracking (activating the window the mouse is on) either on or off. Set pvParam to TRUE for on or FALSE for off.

SPI_SETACTIVEWNDTRKZORDER

Determines whether or not windows activated through active window tracking should be brought to the top. SetpvParam to TRUE for on or FALSE for off.

SPI_SETACTIVEWNDTRKTIMEOUT

Sets the active window tracking delay. Set pvParam to the number of milliseconds to delay before activating the window under the mouse pointer.

SPI_SETANIMATION

Sets the animation effects associated with user actions. The pvParam parameter must point to anANIMATIONINFO structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(ANIMATIONINFO).

SPI_SETBORDER

Sets the border multiplier factor that determines the width of a window's sizing border. The uiParam parameter specifies the new value.

SPI_SETCARETWIDTH

Sets the caret width in edit controls. Set pvParam to the desired width, in pixels. The default and minimum value is 1.

SPI_SETDRAGFULLWINDOWS

Sets dragging of full windows either on or off. TheuiParam parameter specifies TRUE for on, or FALSE for off.

SPI_SETDRAGHEIGHT

Sets the height, in pixels, of the rectangle used to detect the start of a drag operation. Set uiParam to the new value. To retrieve the drag height, callGetSystemMetrics with the SM_CYDRAG flag.

SPI_SETDRAGWIDTH

Sets the width, in pixels, of the rectangle used to detect the start of a drag operation. Set uiParam to the new value. To retrieve the drag width, callGetSystemMetrics with the SM_CXDRAG flag.

SPI_SETFOREGROUNDFLASHCOUNT

Sets the number of times SetForegroundWindow will flash the taskbar button when rejecting a foreground switch request. Set pvParam to the number of times to flash.

SPI_SETFOREGROUNDLOCKTIMEOUT

Sets the amount of time following user input, in milliseconds, during which the system does not allow applications to force themselves into the foreground. SetpvParam to the new timeout value.

The calling thread must be able to change the foreground window, otherwise the call fails.

SPI_SETMINIMIZEDMETRICS

Sets the metrics associated with minimized windows. The pvParam parameter must point to aMINIMIZEDMETRICS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter to sizeof(MINIMIZEDMETRICS).

SPI_SETNONCLIENTMETRICS

Sets the metrics associated with the nonclient area of nonminimized windows. The pvParam parameter must point to a NONCLIENTMETRICS structure that contains the new parameters. Set the cbSize member of this structure and the uiParam parameter tosizeof(NONCLIENTMETRICS). Also, the lfHeight member of the LOGFONT structure must be a negative value.

SPI_SETSHOWIMEUI

Sets whether the IME status window is visible or not on a per-user basis. The uiParam parameter specifies TRUE for on or FALSE for off.

Windows Me/98/95: The following parameters are specific to this platform.
ParameterMeaning

SPI_GETWINDOWSEXTENSION

Windows 95: Determines whether the Windows extension, Windows Plus!, is installed. Set the uiParamparameter to 1. The pvParam parameter is not used. The function returns TRUE if the extension is installed, or FALSE if it is not.

SPI_SETPENWINDOWS

Windows Me/98/95: Pen windows is being loaded or unloaded. The uiParam parameter is TRUE when loading and FALSE when unloading pen windows. ThepvParam parameter is NULL.

SPI_SETSCREENSAVERRUNNING

Windows Me/98: Used internally; applications should not use this flag.
uiParam

A parameter whose usage and format depends on the system parameter being queried or set. For more information about system-wide parameters, see the uiAction parameter. If not otherwise indicated, you must specify zero for this parameter.

pvParam

A parameter whose usage and format depends on the system parameter being queried or set. For more information about system-wide parameters, see the uiAction parameter. If not otherwise indicated, you must specify NULL for this parameter.

fWinIni

If a system parameter is being set, specifies whether the user profile is to be updated, and if so, whether the WM_SETTINGCHANGE message is to be broadcast to all top-level windows to notify them of the change.

This parameter can be zero if you don't want to update the user profile or broadcast the WM_SETTINGCHANGE message, or it can be one or more of the following values.

ValueMeaning

SPIF_UPDATEINIFILE

Writes the new system-wide parameter setting to the user profile.

SPIF_SENDCHANGE

Broadcasts the WM_SETTINGCHANGE message after updating the user profile.

SPIF_SENDWININICHANGE

Same as SPIF_SENDCHANGE.

Return Value

If the function succeeds, the return value is a nonzero value.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

This function is intended for use with applications that allow the user to customize the environment.

A keyboard layout name should be derived from the hexadecimal value of the language identifier corresponding to the layout. For example, U.S. English has a language identifier of 0x0409, so the primary U.S. English layout is named "00000409." Variants of U.S. English layout, such as the Dvorak layout, are named "00010409," "00020409" and so on. For a list of the primary language identifiers and sublanguage identifiers that make up a language identifier, see the MAKELANGID macro.

There is a difference between the High Contrast color scheme and the High Contrast Mode. The High Contrast color scheme changes the system colors to colors that have obvious contrast; you switch to this color scheme by using the Display Options in the control panel. The High Contrast Mode, which uses SPI_GETHIGHCONTRAST and SPI_SETHIGHCONTRAST, advises applications to modify their appearance for visually-impaired users. It involves such things as audible warning to users and customized color scheme (using the Accessibility Options in the control panel). For more information, see HIGHCONTRAST. For more information on general accessibility features, see Accessibility.

During the time that the primary button is held down to activate the Mouse ClickLock feature, the user can move the mouse. Once the primary button is locked down, releasing the primary button does not result in a WM_LBUTTONUP message. Thus, it will appear to an application that the primary button is still down. Any subsequent button message releases the primary button, sending a WM_LBUTTONUP message to the application, thus the button can be unlocked programmatically or through the user clicking any button.

Example Code

For an example, see Getting Hardware Information.

Requirements

Client

Requires Windows Vista, Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.

Server

Requires Windows Server 2008, Windows Server 2003, Windows 2000 Server, or Windows NT Server.

Header

Declared in Winuser.h; include Windows.h.

Library

Use User32.lib.

DLL

Requires User32.dll.

Unicode

Implemented as SystemParametersInfoW (Unicode) and SystemParametersInfoA(ANSI).

See Also

ACCESSTIMEOUT
ANIMATIONINFO
AUDIODESCRIPTION
FILTERKEYS
HIGHCONTRAST
ICONMETRICS
LOGFONT
MAKELANGID
MINIMIZEDMETRICS
MOUSEKEYS
NONCLIENTMETRICS
RECT
SERIALKEYS
SOUNDSENTRY
STICKYKEYS
TOGGLEKEYS
WM_SETTINGCHANGE

'NativeCode > mfc' 카테고리의 다른 글

Static Control 일반적 내용  (0) 2010.03.18
Static Control Font 설정  (0) 2010.03.18
Timer Callback  (0) 2010.03.18
Tray(소스 有)  (0) 2010.03.18
Tray Icon Refresh  (0) 2010.03.18

static void CALLBACK EXPORT TimerProc( HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime );


void CALLBACK EXPORT CPacketSenderDlg::TimerProc( HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime )

{

}

'NativeCode > mfc' 카테고리의 다른 글

Static Control Font 설정  (0) 2010.03.18
SystemParametersInfo  (0) 2010.03.18
Tray(소스 有)  (0) 2010.03.18
Tray Icon Refresh  (0) 2010.03.18
메뉴이벤트 등록하기  (0) 2010.03.18

아주 쉽게 트레이를 만들었다. 소스 첨부할께염. 3개임 트레이등록과 삭제 그리고 리프레쉬

Tray.zip <-트레이소스임!!


tray.bmp


void CH7TrayDlg::RegistTrayIcon()

{

NOTIFYICONDATA  nid;

nid.cbSize = sizeof(nid); // 구조체의 크기

nid.hWnd = m_hWnd; // 메인 윈도우 핸들

nid.uID = IDR_MAINFRAME;  // 아이콘 리소스 ID

nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; // 플래그 설정

nid.uCallbackMessage = WM_TRAYICON_MSG; // 콜백메시지 설정

nid.hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); // 아이콘 로드 

lstrcpy(nid.szTip, "Long live the Queen");


Shell_NotifyIcon(NIM_ADD, &nid); // Tray Icon을 시스템에 등록

SendMessage(WM_SETICON, (WPARAM)TRUE, (LPARAM)nid.hIcon);

m_bIsTrayIcon = TRUE; // tray 등록되었다는 플래그 설정


// sMenu = new CMenu; // tray icon이 눌렸을때 팝업될 메뉴

// sMenu->LoadMenu(IDR_MENU1);

}


void CH7TrayDlg::DestroyTrayIcon()

{

if( m_bIsTrayIcon ) // 현재 트레이 아이콘으로 설정되었는지 확인 

{

//delete sMenu;


NOTIFYICONDATA  nid;

nid.cbSize = sizeof(nid);

nid.hWnd = m_hWnd; // 메인 윈도우 핸들

nid.uID = IDR_MAINFRAME;


// 작업 표시줄(TaskBar)의 상태 영역에 아이콘을 삭제한다.

Shell_NotifyIcon(NIM_DELETE, &nid);


TeleShellTrayRefresh::Refresh();

}

}


'NativeCode > mfc' 카테고리의 다른 글

SystemParametersInfo  (0) 2010.03.18
Timer Callback  (0) 2010.03.18
Tray Icon Refresh  (0) 2010.03.18
메뉴이벤트 등록하기  (0) 2010.03.18
트레이아이콘으로 이동하는 애니메이션  (0) 2010.03.18

By 유광희, 2006.10.17

소개


 쉘 트레이를 이용하는 S/W 를 개발하거나, 이용하는 입장에서

프로세스가 죽었음에도 트레이 영역에 남아 있는 아이콘을 제거하기 위해 만든 함수 입니다 !


쉘 트레이 아이콘 ?


 
위처럼 어느 윈도우에서나 볼수 있는 쉘 트레이는 Toolbar 컨트롤로서 어플리케이션 아이콘을 트레이

영역에 생성하여 이벤트를 처리하는 영역입니다.

MSDN - Toolbar Controls


쓰레기 Tray 아이콘이란 ?


 < ActiveSync 가 강제 종료되어 쓰레기 아이콘이 3개나 보인다 >

트레이에 아이콘을 생성해둔 프로그램이 강제로 종료되었을때, 만들어진 트레이 아이콘을
삭제하지 못하고 종료된 경우 입니다.

개발자 측에서는 트레이 아이콘을 생성하는 기능이 들어갈 경우 쓰레기와 더불어 
지저분해진 트레이 아이콘이 같이 보이게 되는데 이러한 현상을 없애기 위해 1회 정도 아래의 함수를 실행하여
깔끔한 트레이를 유지하는 방법입니다

쓰레기 아이콘의 제거는 어떻게 ?

1. 윈도우에서 트레이 아이콘의 윈도우 핸들을 찾는다
2. 해당 윈도우에서 Toolbar 컨트롤을 찾는다
3. 컨트롤에서 트레이 아이콘의 개수를 얻는다
4. TB_BUTTONCOUNT 을 이용하여 현재 트레이에 등록된 아이콘의 개수를 얻는다
5. 해당 개수만큼 TB_GETBUTTON 을 툴바 윈도우에 요청하기 위하여
5.1 해당 프로세서의 PID 를 구한다
5.2 해당 프로세서 내에 가상 메모리를 생성
5.3 TB_GETBUTTON 에서 리턴받을 메모리를 TRAY 프로세서의 가상 메모리에 할당한다
5.4 TB_GETBUTTON 요청하여 TRAYDATA 라는 구조체에 넣는다

6. TRAY 구조체 내에 ProcessID 가 NULL 일 경우 해당 아이콘을 삭제
7. 5의 위치로 아이콘만큼 반복 8. 가상 메모리 해제 및 끝

가상 메모리는 왜 ?

시스템 트레이 아이콘이 위치한 윈도우 핸들도 하나의 프로세스 내에 위치합니다
TB_BUTTONCOUNT 는 리턴이 int 형이라 관련이 없지만
TB_GETBUTTON 와 같은 데이터의 리턴값을 분석해야 할 필요가 있는 메세지는
해당 프로세서내의 메모리에서 생성된 값으로 리턴받아야 합니다.
왜.. 서로 다른 프로세서끼리는 일반적인 변수나 할당한 메모리는 공유가 안되기에.. (다들 알죠?) 
그리하여 해당 프로세서를 이용하여 가상의 메모리를 만들어 해당 데이터를 리턴받게 됩니다.

관련 구조체소스

TBBUTTON(commctrl.h)

typedef struct _TBBUTTON { int iBitmap; int idCommand; BYTE fsState; BYTE fsStyle; #ifdef _WIN64 BYTE bReserved[6] // padding for alignment #elif defined(_WIN32) BYTE bReserved[2] // padding for alignment #endif DWORD_PTR dwData; INT_PTR iString; } TBBUTTON, NEAR *PTBBUTTON *LPTBBUTTON;

NOTIFYICONDATA(shellapi.h)

typedef struct _NOTIFYICONDATA { DWORD cbSize; HWND hWnd; UINT uID; UINT uFlags; UINT uCallbackMessage; HICON hIcon; TCHAR szTip[64]; DWORD dwState; DWORD dwStateMask; TCHAR szInfo[256]; union { UINT uTimeout; UINT uVersion; }; TCHAR szInfoTitle[64]; DWORD dwInfoFlags; GUID guidItem; HICON hBalloonIcon; } NOTIFYICONDATA, *PNOTIFYICONDATA;

소스

/******************************************************************* FileName: TeleShellTrayRefresh.cpp Description: 사라진 트레이 아이콘을 정리한다! CREATED: 2006-09-12 LAST MODIFIED 2006-09-12 BY: KwangHee Yoo cpueblo@cpueblo.com, yurchi@hanmail.net http://www.cpueblo.com ***********************************************************************/ //========================================================= // INCLUDE 헤더 정의. MFC 용과 빌더용, 또는 자신의 Preheader 해더 파일로 대체 //========================================================= #include ; #include //========================================================= // 구조체 정의 //========================================================= struct TRAYDATA { HWND hwnd; UINT uID; UINT uCallbackMessage; DWORD Reserved[2]; HICON hIcon; }; //========================================================= // Tray 아이콘의 프로세스 이름을 얻기 위해 윈도우 핸들을 얻는 함수 //========================================================= static HWND FindTrayToolbarWindow() { HWND hWnd_ToolbarWindow32 = NULL; HWND hWnd_ShellTrayWnd; hWnd_ShellTrayWnd = ::FindWindow(_T("Shell_TrayWnd"), NULL); if(hWnd_ShellTrayWnd) { HWND hWnd_TrayNotifyWnd = ::FindWindowEx(hWnd_ShellTrayWnd,NULL,_T("TrayNotifyWnd"), NULL); if(hWnd_TrayNotifyWnd) { HWND hWnd_SysPager = ::FindWindowEx(hWnd_TrayNotifyWnd,NULL,_T("SysPager"), NULL); // WinXP // WinXP 에서는 SysPager 까지 추적 if(hWnd_SysPager) { hWnd_ToolbarWindow32 = ::FindWindowEx(hWnd_SysPager, NULL,_T("ToolbarWindow32"), NULL); } // Win2000 일 경우에는 SysPager 가 없이 TrayNotifyWnd -> ToolbarWindow32 로 넘어간다 else { hWnd_ToolbarWindow32 = ::FindWindowEx(hWnd_TrayNotifyWnd, NULL,_T("ToolbarWindow32"), NULL); } } } return hWnd_ToolbarWindow32; } //========================================================= // 생성자 //========================================================= TeleShellTrayRefresh::TeleShellTrayRefresh() { } //========================================================= // 소멸자 //========================================================= TeleShellTrayRefresh::~TeleShellTrayRefresh() { } //========================================================= // Refresh 의 메인 //========================================================= bool TeleShellTrayRefresh::Refresh() { try { HANDLE m_hProcess; LPVOID m_lpData; TBBUTTON tb; TRAYDATA tray; DWORD dwTrayPid; int TrayCount; // Tray 의 윈도우 핸들 얻기 HWND m_hTrayWnd = FindTrayToolbarWindow(); if (m_hTrayWnd == NULL) return false; // Tray 의 개수를 구하고 TrayCount = (int)::SendMessage(m_hTrayWnd, TB_BUTTONCOUNT, 0, 0); // Tray 윈도우 핸들의 PID 를 구한다 GetWindowThreadProcessId(m_hTrayWnd, &dwTrayPid); // 해당 Tray 의 Process 를 열어서 메모리를 할당한다 m_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwTrayPid); if (!m_hProcess) return false; // 해당 프로세스 내에 메모리를 할당 m_lpData = VirtualAllocEx(m_hProcess, NULL, sizeof (TBBUTTON), MEM_COMMIT, PAGE_READWRITE); if (!m_lpData) return false; // Tray 만큼 뺑뺑이 for(int i = 0; i < TrayCount; i++) { ::SendMessage(m_hTrayWnd, TB_GETBUTTON, i, (LPARAM)m_lpData); // TBBUTTON 의 구조체와 TRAYDATA 의 내용을 얻기 ReadProcessMemory(m_hProcess, m_lpData, (LPVOID)&tb, sizeof (TBBUTTON), NULL); ReadProcessMemory(m_hProcess, (LPCVOID)tb.dwData, (LPVOID)&tray, sizeof (tray), NULL); // 각각 트레이의 프로세스 번호를 얻어서 DWORD dwProcessId = 0; GetWindowThreadProcessId(tray.hwnd, &dwProcessId); // Process 가 없는 경우 TrayIcon 을 삭제한다 if (dwProcessId == 0) { NOTIFYICONDATA icon; icon.cbSize = sizeof(NOTIFYICONDATA); icon.hIcon = tray.hIcon; icon.hWnd = tray.hwnd; icon.uCallbackMessage = tray.uCallbackMessage; icon.uID = tray.uID; Shell_NotifyIcon(NIM_DELETE, &icon); } } // 가상 메모리 해제와 프로세스 핸들 닫기 VirtualFreeEx(m_hProcess, m_lpData, NULL, MEM_RELEASE); CloseHandle(m_hProcess); return true; } catch (...) { return false; } }

관련 링크

MSDN - TB_BUTTONCOUNT
MSDN - TB_GETBUTTON

예제와 소스 다운로드

다운로드

작성자

http://cpueblo.com

유광희


'NativeCode > mfc' 카테고리의 다른 글

Timer Callback  (0) 2010.03.18
Tray(소스 有)  (0) 2010.03.18
메뉴이벤트 등록하기  (0) 2010.03.18
트레이아이콘으로 이동하는 애니메이션  (0) 2010.03.18
날짜구하기  (0) 2010.03.18

void CH7TrayDlg::OnMenuId( UINT id )

{

switch( id )

{

case 31001: // 숨기기

this->ShowWindow( SW_SHOW );

break;


case 31002: // 종료

this->DestroyWindow();

break;


default:

break;

}

}


ON_COMMAND_RANGE( 31001, 31002, OnMenuId )

afx_msg void OnMenuId( UINT id );

'NativeCode > mfc' 카테고리의 다른 글

Tray(소스 有)  (0) 2010.03.18
Tray Icon Refresh  (0) 2010.03.18
트레이아이콘으로 이동하는 애니메이션  (0) 2010.03.18
날짜구하기  (0) 2010.03.18
문자열 포맷 변환  (0) 2010.03.18

Snap5.bmp


void CH7TrayDlg::ShowToTray( HWND hWnd )

{

RECT rectFrom;

RECT rectTo;

::GetWindowRect( hWnd, &rectFrom );



::SystemParametersInfo( SPI_GETWORKAREA, 0, &rectTo, 0 );

rectTo.left = rectTo.right - 70;

rectTo.top = rectTo.bottom - 10;


::DrawAnimatedRects( hWnd, IDANI_CAPTION, &rectFrom, &rectTo );



::ShowWindow( hWnd, SW_HIDE );

}

'NativeCode > mfc' 카테고리의 다른 글

Tray Icon Refresh  (0) 2010.03.18
메뉴이벤트 등록하기  (0) 2010.03.18
날짜구하기  (0) 2010.03.18
문자열 포맷 변환  (0) 2010.03.18
파일 검색, 복사 하위 경로 포함(소스 파일 有)  (0) 2010.03.18

1. 현재시간 구할때

CTime t = CTime::GetCurrentTime();


2. 그 시간을 정수로 사용할때

t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(),   t.GetMinute(), t.GetSecond(), t.GetDayOfWeek()


3. 정수로 CTime을 만들때

    CTime from(2007, 5, 29, 0, 0, 0);
    CTime to(2007, 5, 29, 23,59,59);


4. 날짜에서 몇일을 뺄때

    CTime pre;

    CTimeSpan ts(10, 0, 0, 0 );  // 10일(일,시,분,초)
    pre = from - ts;


5. 날짜에서 날짜를 빼고, 시간차가 1시간 초과이면...

  CTimeSpan diff = CTime::GetCurrentTime() - m_time;
  if(diff.GetTotalSeconds() > 3600) ...


Snap1.jpg

'NativeCode > mfc' 카테고리의 다른 글

메뉴이벤트 등록하기  (0) 2010.03.18
트레이아이콘으로 이동하는 애니메이션  (0) 2010.03.18
문자열 포맷 변환  (0) 2010.03.18
파일 검색, 복사 하위 경로 포함(소스 파일 有)  (0) 2010.03.18
파일 찾기  (0) 2010.03.18

Micorsoft Foundation Class Know How

1) CString 클래스


함수

내용

GetLength

설정된 문자의 길이를 반환

IsEmpty

현재 클래스에 문자열 버퍼가 비워 있는가?

Empty

문자열을 삭제하여 버퍼를 비운다.

GetAt

문자열의 특정 위치의 문자 값을 얻는다.

SetAt

문자열의 특정 위치에 새로운 문자를 삽입한다.

Compare

문자열과 인자의 문자열을 비교한다.

MakeUpper

문자열의 소문자를 대문자로 바꾼다.

MakeLower

문자열의 대문자를 소문자로 바꾼다.

Format

문자열에 형식을 갖추어 문자들을 넣는다.

Find

문자열에서 특정 문자나 문자열을 찾는다.

2) 헝가리안 표기법


접두어

데이터타입

접두어

데이터 타입

a

배열(Array)

i

인덱스

b

BOOL

l

long int

ch

character

lp

long(far) pointer

cb

count of bytes

n

int

dw

unsigned long DWORD

sz

NULL로 끝나는 문자열

h

Handle

w

unsined int WORD

3) string 형 char *에 복사

const char *std::string.c_str(); char*으로 반환

strcpy( ( char * ) , std::string.c_str() ); char *에 string의 값 반환.


4) CString <-> std::string

1, CString -> std::string

CString str = "hello";

std::string stdStr = str.GetBuffer(0);

2. std::string -> CString

std::string stdStr = "hello";

CString str = stdStr.c_str();

4번 잘 안됨. 나중에 다시 고칠것


5)char * 형에 string, CString 값 넣기

char *pStr = (LPSTR)string.data();

char *pStr = (LPSTR)(LPCTSTR)cstring;6


6) CString, TCHAR -> LPCSTR, LPCWSTR 등 형으로 변환

MultiByteToWideChar( CP_ACP, 0, CString, CString.Length(), ( LPWSTR )LPCWSTR, sizeof( CString ) );


7) Debug Assertion Failed!

원인: 배열의 마지막 원소를 Null로 처리를 안해준다거나 할 때 발생하는 것.

DoDataExchange()에서 에디트 컨트롤(DDX)를 제대로 지워 주지 않았음.

멀티스레드 사용. 동기화는 안함.

파일_찾고_원하는_경로에_복사.zip


'NativeCode > mfc' 카테고리의 다른 글

날짜구하기  (0) 2010.03.18
문자열 포맷 변환  (0) 2010.03.18
파일 찾기  (0) 2010.03.18
폴더 선택 다이알로그 BROWSEINFO  (0) 2010.03.18
하위 경로까지의 모든 파일 목록 얻기  (0) 2010.03.18

CFileFind find;

CString lRunFilName, fileName;

char lProgramPath[ 255 ];


int i = -2; // 현재 폴더를 나타내는 포인터와 상위폴더를 나타내는 포인터의 갯수를 뺀다.


GetModuleFileName( NULL, lProgramPath, _MAX_PATH );

lRunFilName = lProgramPath;

lRunFilName.Delete( lRunFilName.ReverseFind( '\\' ) + 1, lRunFilName.GetLength() - lRunFilName.ReverseFind( '\\' ) );

lRunFilName += "UpdataFiles\\";

lRunFilName += "*.*";


BOOL bFileExist = false;

bFileExist = find.FindFile( lRunFilName );


while( bFileExist )

{

bFileExist = find.FindNextFile();

fileName = find.GetFileName();

i ++;

}


이 소스는 원하는 폴더에 파일 갯수가 몇개 있는지 알려준다.

BOOL cfile.IsDots(); 현재 해당 파일이 상위폴더를 가르키는 파일 포인터인지를 판별해주는 함수임.    

cfile.IsDirectory(); 현재 해당 파일이 폴더인지를 판별해주는 함수.

CString cfile.GetFileName(); 현재 해당 파일의 이름을 반환

CString cfile.GetFilePath(); 현재 해당 파일의 전체경로를 반환

ULONGLONG cfile.GetLength(); 파일의 크기를 byte크기로 반환


BOOL cfile.GetCreationTime(CTime &refTime); 파일의 생성 수정 시간을 CTime형식으로 참조 반환



 ITEMIDLIST        *pidlBrowse;
  char    pszPathname[MAX_PATH];

  BROWSEINFO BrInfo;
  BrInfo.hwndOwner = NULL; //GetSafeHwnd();
  BrInfo.pidlRoot = NULL;

  memset( &BrInfo, 0, sizeof(BrInfo) );
  BrInfo.pszDisplayName = pszPathname;
  BrInfo.lpszTitle = "복사할 디렉토리를 선택하세요";
  BrInfo.ulFlags = BIF_RETURNONLYFSDIRS;



  // 다이얼로그를 띄우기
  pidlBrowse = ::SHBrowseForFolder(&BrInfo);   



  if( pidlBrowse != NULL)
  {
     // 패스를 얻어옴
     ::SHGetPathFromIDList(pidlBrowse, pszPathname);    
  }

'NativeCode > mfc' 카테고리의 다른 글

파일 검색, 복사 하위 경로 포함(소스 파일 有)  (0) 2010.03.18
파일 찾기  (0) 2010.03.18
하위 경로까지의 모든 파일 목록 얻기  (0) 2010.03.18
현재 위치 구하기  (0) 2010.03.18
프로세스 찾아 죽이기  (0) 2010.03.18

SearchDirectory( "g:\\공부 문서\\" );

list< char * > m_ListTotalFileName;


int CFileDlg::SearchDirectory(const char *parm_search_path)

{

CString search_path = parm_search_path;

char *pFileName;

int nSearchPathLen;



WIN32_FIND_DATA file_data;

// 현재 경로의 모든 파일과 디렉토리를 찾는다.

HANDLE search_handle = FindFirstFile(search_path + "*.*", &file_data);

if(INVALID_HANDLE_VALUE != search_handle){

do{

if(FILE_ATTRIBUTE_DIRECTORY & file_data.dwFileAttributes)

{

// 폴더인 경우...

// 현재 폴더(.)와 이전폴더("..")를 의미하는 심볼은 제외시킨다.

if(file_data.cFileName[ 0 ] != '.')

{

// 서브 디렉토리를 계속 검색한다.

SearchDirectory(search_path + file_data.cFileName + CString("\\") );

}

else 

{

m_CListBox.InsertString(-1, "[FILE]: " + search_path + file_data.cFileName);

m_TotalCount ++;

m_TotalBytes += file_data.nFileSizeLow;


pFileName = new char [ MAX_PATH ];

nSearchPathLen = strlen( search_path );

strcpy_s( pFileName, nSearchPathLen + 1, search_path );

strcpy_s( pFileName + nSearchPathLen, strlen( file_data.cFileName ) + 1, file_data.cFileName );

m_ListTotalFileName.push_back( pFileName );

}

} while(FindNextFile(search_handle, &file_data));

FindClose(search_handle);

}


return 0;

}


'NativeCode > mfc' 카테고리의 다른 글

파일 찾기  (0) 2010.03.18
폴더 선택 다이알로그 BROWSEINFO  (0) 2010.03.18
현재 위치 구하기  (0) 2010.03.18
프로세스 찾아 죽이기  (0) 2010.03.18
하드 용량 체크  (0) 2010.03.18

CString lRunFilName;

char lProgramPath[ 255 ];


GetModuleFileName( NULL, lProgramPath, _MAX_PATH );

lRunFilName = lProgramPath;

lRunFilName.Delete( lRunFilName.ReverseFind( '\\' ) + 1, lRunFilName.GetLength() - lRunFilName.ReverseFind( '\\' ) );

lRunFilName += "lex.exe";

'NativeCode > mfc' 카테고리의 다른 글

파일 찾기  (0) 2010.03.18
폴더 선택 다이알로그 BROWSEINFO  (0) 2010.03.18
하위 경로까지의 모든 파일 목록 얻기  (0) 2010.03.18
프로세스 찾아 죽이기  (0) 2010.03.18
하드 용량 체크  (0) 2010.03.18

#include <tlhelp32.h>


bool CH7TrayDlg::KillProcess( CString sExeName )

sExeName.MakeUpper(); 

HANDLE hSnapshot = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS, 0 ); 

if ( (int)hSnapshot != -1 ) 

PROCESSENTRY32 pe32 ; 

pe32.dwSize=sizeof(PROCESSENTRY32); 

BOOL bContinue ; 

CString strProcessName; 

if ( Process32First ( hSnapshot, &pe32 ) ) 

do 

strProcessName = pe32.szExeFile; //strProcessName이 프로세스 이름; 

strProcessName.MakeUpper(); 

if( ( strProcessName.Find("H7.EXE",0) != -1 ) ) 

HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, 0, pe32.th32ProcessID ); 

if( hProcess ) 

DWORD       dwExitCode; 

GetExitCodeProcess( hProcess, &dwExitCode); 

TerminateProcess( hProcess, dwExitCode); 

CloseHandle(hProcess); 

CloseHandle( hSnapshot ); 

return TRUE; 

return FALSE; 

bContinue = Process32Next ( hSnapshot, &pe32 ); 

} while ( bContinue ); 

CloseHandle( hSnapshot ); 

return FALSE;

}

'NativeCode > mfc' 카테고리의 다른 글

파일 찾기  (0) 2010.03.18
폴더 선택 다이알로그 BROWSEINFO  (0) 2010.03.18
하위 경로까지의 모든 파일 목록 얻기  (0) 2010.03.18
현재 위치 구하기  (0) 2010.03.18
하드 용량 체크  (0) 2010.03.18

void CDiskInfo::SearchDisk()
{
      DWORD   dwDiskInfo;
      int    i, nCount;

      InitDiskInfo();
      dwDiskInfo = GetLogicalDrives();

      for( i = 0 ; i < DISK_COUNT ; i ++ )
      {
            if( ( dwDiskInfo & m_dwDiskDriveData[i] ) != 0x0000 )
            {
                  CString  strDrive;
                  strDrive += 'A' + i;
                  strDrive += ":\\";
                  m_arrayDiskDriver.Add(strDrive);
            }
      }

      char  szDrive[MAX_PATH];
      GetLogicalDriveStrings(MAX_PATH, szDrive);
      // szDrive를 파싱하여 드라이브 목록을 얻어 올 수 있다.

      nCount = m_arrayDiskDriver.GetUpperBound() + 1;
      m_nTotalDisk = nCount;
      for( i = 0 ; i < nCount ; i ++ )
      {
            DISK_INFO_DATA  diskData;
            diskData.strDrive = m_arrayDiskDriver.GetAt(i);
            SearchDiskInfo(m_arrayDiskDriver.GetAt(i), &diskData);
            m_arrayDiskSize.Add(diskData);
      }
}


GetLogicalDirves는 현재 컴퓨터의 Dirve 목록을 DWORD의 각 비트별로 채워주는 함수 있습니다. 이부분에 대한 설명을 생략하도록 하겠습니다. 소스에 있는 GetLogicalDirveStrings가 조금 더 쉬울 수도 있습니다.

아무튼 이런 과정을 통해서 컴퓨터 내의 드라이브 전체 목록을 얻어 오고 각 드라이브 명을 C:\ 이런 식으로 저장합니다.


SearchDiskInfo를 살펴 보도록 하겠습니다.


void CDiskInfo::SearchDiskInfo(LPCTSTR lpDriver, LPDISK_INFO_DATA lpData)
{
      LONGLONG  lFreeBytesAvailable, lTotalBytes, lTotalFree;
      UINT   DiskType;
 
      DiskType = GetDriveType(lpDriver);
      lpData->diskType = DiskType;
 
      if( DiskType == DRIVE_FIXED ) // 고정 디스크(Hard Disk)일 경우만 디스크 크기를 구한다.
      {
            GetDiskFreeSpaceEx(lpDriver, (PULARGE_INTEGER)&lFreeBytesAvailable, (PULARGE_INTEGER)&lTotalBytes, (PULARGE_INTEGER)&lTotalFree);
  
            lpData->lDiskFreeSize = lTotalFree;
            lpData->lDiskSize = lTotalBytes;
      }
      else       // 플로피, 시디롬등의 용량은 0으로 한다.
      {
            lpData->lDiskFreeSize = 0;
            lpData->lDiskSize = 0;
      }
}


생각보도 간단 합니다. DIskType을 검사해서 고정디스크 인 경우만 용량을 확인 합니다. 구지 설명을 드리지 않아도 이해하실 수 있을 것 같습니다. DISK_INFO_DATA는 제가 사용하기 위해서 만든 구조체 입니다. 소스를 보시면 이해하실 수 있을 것입니다.


이렇게 컴퓨터 전체 드라이브의 용량을 조사 한 후 GUI를 통해서 보여 주기만 하면 됩니다. 제가 만든 프로그램은 GUI가 허접하니 잘 만들어 보시길 ^^

'NativeCode > mfc' 카테고리의 다른 글

파일 찾기  (0) 2010.03.18
폴더 선택 다이알로그 BROWSEINFO  (0) 2010.03.18
하위 경로까지의 모든 파일 목록 얻기  (0) 2010.03.18
현재 위치 구하기  (0) 2010.03.18
프로세스 찾아 죽이기  (0) 2010.03.18

1. 새로운 테이블의 생성(CREATE TABLE)


CREATE TABLE 테이블명(

필드명 데이터타입 [NOT NULL]

{, 필드명 데이터타입 [NOT NULL]}*

[, PRIMARY KEY(필드명)]

)


ex) CREATE TABLE userdb (   

      name CHAR(8),                            //CHAR 문자수가 M개인 문자열을 뜻한다.

      id VARCHAR(10) NOT NULL,          //VARCHAR 문자수가 최대 M개인 문자열을  뜻한다.

      email VARCHAR(40),

      sex CHAR(1),

      PRIMARY KEY(id)

      )


2. 생성된 테이블의 변경(ALTER TABLE)

:생성하면서 미처 정의하지 못한 필드를 추가할수 있으며, 데이터 타입도 바꿀수 있다.

ALTER TABLE user add name VARCHAR(30)      
  //필드추가

or

CHANGE [COLUMN] 기존필드명 새필드명 필드타입        //필드속성 변경

or

ALTER TABLE user DROP [COLUMN] 필드명                //필드삭제


ex) ALTER TABLE 테이블명 ADD addr VARCHAR(100)    //주소 필드를 추가


     ARTER TABLE 테이블명 CHANGE addr address VARCHAR(255) 

    // 주소필드(addr)의 이름을 address로 수정. 또한 글자수도 최대 255자로 변경.


3. 생성된 테이블의 삭제(DROP TABLE)

DROP TABLE 테이블명


4. 데이터 검색(SELECT)


SELECT [DISTINCT] 필드명 {, 필드명}*

FROM 테이블명 {, 테이블명}*

[WHERE 조건검색]

[ORDER BY 필드명[ASC or DESC] {, 필드명 [ASC or DESC]}*]

[GRUB BY 필드명 {, 필드명}*]

[HAVING 검색조건]


ex) SELECT name, id FROM userdb WHERE level = 'B'


//테이블 userdb에서 사용자 등급이 'B'인 사용자의 레코드를 찾아서 사용자의 이름과 아이디 필드를 출력한다.


검색 중복 제거

SELECT DISTINCTlevel FROM userdb


조건 검색 (WHERE)

SELECT name, id, email FROM userdb WHERE milage > 3000 AND sex = 'M'

// 마일리지가 3천이하이고, 남자를 검색.

WHERE절에는 비교연산자 >,>=,<,<=,=와 AND,OR,NOT같은 연산자를 사용할수 있다.


검색결과의 정렬 (ORDER ~DESC or ASC)

SELECT name,id,milage FROM userdb WHERE milage >= 3000 ORDER BY milge >= 3000 ORDER BY milage DESC

//마일리지가 3천 이상인 사람의 이름, 아이디, 마일리지를 출력하되 마일리지가 높은 순으로 출력.


SELECT name, id, milage FROM userdb WHERE milage >= 3000 ORDER BY milage ASC

or

SELECT name, id, milage FROM userdb WHERE milage >= 3000 ORDER BY milage


오름차순 정렬 : ASC,  내림차순 정렬 : DESC,  명령어 없을땐 오름차순으로 정렬됨.


산술 계산  문자열 처리

SELECT name, '님의 마일리지는 ', milage, '점 입니다' FROM userdb WHERE milage >= 3000 ORDER BY milage


그룹 함수를 이용한 검색

count (필드명)      //조건을 만족하는 레코드의 개수

sum   (필드명)      //해당 필드값의 합

min    (필드명)      //해당 필드의 값중 최소값

max   (필드명)      //해당 필드의 값중 최대값

avg    (필드명)      //해당 필드의 평균값


ex) SELECT count(*) FROM user WHERE sex = 'F'

//user 테이블에서 여성사용자가 몇 명이나 되는지를 함수로 검색.

     SELECT avg(milage) FROM user WHERE sex = 'F'

//user 테이블에서 여성사용자들의 평균 마일리지 값을 출력한다.


GROUP BY를 이용한 검색

기본구조

SELECT sex, max(milage), min(milage), avg(milage) FROM 테이블명 GROUP BY sex


HAVING을 이용한 검색

: group by로 지정한 필드에 대하여 추가로 검색 조건을 지정할 때 사용한다.

기본구조

SELECT sex, max(milage), min(milage), avg(milage) FROM user GROUP BY sex HAVING sex = 'F'


BETWEEN~AND IN 연산자를 이용한 검색

: 마일리지가 3000이상 4000이하인 여자의 이름과 이메일, 마일리지, 성별을 출력한다.

SELECT name, email, milage, sex FROM user WHERE sex = 'F' AND milage BETWEEN 3000 AND 4000;


LIKE를 이용한 검색

: WHERE 조건절에서 가장 많이 사용하는 검색 조건 연산자이며 보통 LIKE 문을 사용하여 필드값의 문자열을 검색한다.

SELECT name FROM user WHERE name LIKE '%현%'

// '현'이라는 문자를 포함하는 모든 레코드를 검색한다. '현%' 은 시작문자중 검색.


NULL 값을 갖는 데이터 검색

: 특정 필드의 값이 NULL 값인 레코드를 검색하기위해 IS NULL문을 사용한다.

SELECT name, id FROM user WHERE email IS NULL


LIMIT 연산자를 이용한 검색

: 검색된 레코드의 개수를 정하여 가져오는 것.

SELECT name, id, milage FROM user LIMIT 3or 1,3 (1부터 3개의 코드를 가져온다)


5. 생성된 테이블의 변경(ALTER TABLE)

ALTER TABLE의 기본 형식

필드추가 - ADD 필드명 필드타입

필드속성 변경 - CHANGE 기존필드명 새필드명 필드타입

필드삭제 - DROP 필드명


ALTER TABLE user ADD COLUMN addr VARCHAR(100)    //생략가능하며 처음 생성시의 타입과

or                                                                                  동일하게 해야됨.

ALTER TABLE user ADD addr VARCHAR(100)


6. 새로운 데이터의 삽입 (INSERT)

INSERT INTO 테이블명 VALUES(필드값: '이현재' ,'sindee' , 639 , ...);

//문자는 작은따옴표를 사용하되 숫자는 그냥 사용.


7. 데이터의 수정 (UPDATE) : 반드시 WHERE 절로 조건을 명시해야 된다.

UPDATE use SET sex = 'F' WHERE name = '이현재'

WHERE 절로 검색 조건을 명시하지 않으면 테이블(use)내의 모든 레코드의 필드값(sex)이 새로 설정한 필드(sex)값으로 수정된다.


8. 데이터의 삭제 (DELETE) : 조건 명시 않으면 모두 삭제된다.

DELETE FROM lee2 [WHERE 검색조건]

DELETE FROM use WHERE id = '관제';

'NativeCode > SQLite Cpp' 카테고리의 다른 글

CppSQLite 사용법. (라이브러리 포함)  (0) 2010.03.18
SqlConnection  (0) 2010.03.18
SqlCommand  (0) 2010.03.18

+ Recent posts