Windows API Tutorials
Здесь есть возможность читать онлайн «Windows API Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:Windows API Tutorials
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:3 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 60
- 1
- 2
- 3
- 4
- 5
Windows API Tutorials: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Windows API Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
Windows API Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Windows API Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
}
Once the Windows class is registered with the system, you can create as many windows of this class as you wish. They will, of course, share the same Window procedure that was registered with the class. We'll see later how we can distinguish between various instances of the window inside the procedure.
The class WinMakerworks in much the same way as WinClass. Its constructor provides sensible defaults that may be overriden by calling particular methods. Once everything is set, you call the Createmethod to create the window and the Showmethod to display it. notice that the moment you call create, your window procedure is called with the wm_create message.
The top window is created using TopWinMaker class, which provides the appropriate style and caption.
class WinMaker{
public:
WinMaker (WinClass & winClass);
operator HWND () {
return _hwnd;
}
void AddCaption (char const * caption) {
_windowName = caption;
}
void AddSysMenu () {
_style |= WS_SYSMENU;
}
void AddVScrollBar () {
_style |= WS_VSCROLL;
}
void AddHScrollBar () {
_style |= WS_HSCROLL;
}
void Create ();
void Show (int nCmdShow = SW_SHOWNORMAL);
protected:
WinClass & _class;
HWND _hwnd;
DWORD _exStyle; // extended window style
char const * _windowName; // pointer to window name
DWORD _style; // window style
int _x; // horizontal position of window
int _y; // vertical position of window
int _width; // window width
int _height; // window height
HWND _hWndParent; // handle to parent or owner window
HMENU _hMenu; // handle to menu, or child-window ID
void * _data; // pointer to window-creation data
};
WinMaker::WinMaker(WinClass & winClass) :
_hwnd (0), _class (winClass), _exStyle (0), // extended window style
_windowName (0), // pointer to window name
_style (WS_OVERLAPPED), // window style
_x (CW_USEDEFAULT), // horizontal position of window
_y (0), // vertical position of window
_width (CW_USEDEFAULT), // window width
_height (0), // window height
_hWndParent (0), // handle to parent or owner window
_hMenu (0), // handle to menu, or child-window identifier
_data (0) // pointer to window-creation data { }
void WinMaker::Create() {
_hwnd = :: CreateWindowEx(
_exStyle,
_class.GetName (),
_windowName,
_style,
_x,
_y,
_width,
_height,
_hWndParent,
_hMenu,
_class.GetInstance (),
_data);
if (_hwnd == 0) throw WinException ("Internal error: Window Creation Failed.");
}
void WinMaker::Show(int ncmdshow) {
::ShowWindow (_hwnd, nCmdShow);
::UpdateWindow (_hwnd);
}
// Makes top overlapped window with caption
TopWinMaker::TopWinMaker((WinClass & winClass, char const * caption) : WinMaker (winClass) {
_style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
_windowName = caption;
}
Before we go any further, here are some light-weight classes of general interest. WinExceptionis something that we want to throw any time a Windows API fails. It takes care of retrieving the windows error code. (By the way, there is an easy way to convert the error code to a string using FormatMessageAPI.)
The class ResStringis a simple encapsulation of a string stored in the string resources of your application.
// The exception class: stores the message and the error code
class WinException{
public:
WinException (char* msg) : _err (:: GetLastError()), _msg(msg) {}
DWORD GetError() const {
return _err;
}
char const * GetMessage () const {
return _msg;
}
private:
DWORD _err;
char * _msg;
};
// The out-of-memory handler: throws exception
int NewHandler(size_t size) {
throw WinException ( "Out of memory" );
return 0;
}
class ResString{
enum { MAX_RESSTRING = 255 };
public:
ResString (HINSTANCE hInst, int resId);
operator char const * () { return _buf; }
private:
char _buf [MAX_RESSTRING + 1];
};
ResString::ResString(hinstance hinst, int resid) {
if (!:: LoadString(hinst, resid, _buf, max_resstring + 1)) throw WinException ("Load String failed");
}
The Controlleris the nervous system of a particular window instance . It is created with that window, stored with it and finally destroyed with it. You can put any state information pertaining to a particular window instance in its controller. In general, the controller has a view that deals with painting on the window's surface and it has access to the model , which is the brain of your application (this is called the MVC, or Model-View-Controller pattern invented by Smalltalk programmers).
If, as it often happens, your application has only one top-level window, you can directly embed the model in its controller. That simplifies the management of resources but at the cost of tight coupling of the controller with the model. In large projects one should avoid such couplings-the use of a (smart) pointer to the model inside the controller is then preferred.
Most controller methods require a handle to the window on which behalf they are operating. This handle is passed with every Windows message, but it is simpler to store it once inside the controller object and use it whenever necessary. Remember-there is a one-to-one correspondence between window instances (and therefore window handles) and controller objects.
class Controller{
public:
Controller(HWND hwnd, CREATESTRUCT * pCreate);
~Controller ();
void Size (int x, int y);
void Paint ();
void Command (int cmd);
private:
HWND _hwnd;
Model _model;
View _view;
};
The Window Procedureis the main switchboard of a windows application. You don't call it from your program — Windows calls it! Every time something interesting happens, Windows sends your program a message. This message is passed to your Window procedure. You may deal with it, or you may pass it on to the default window procedure .
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Windows API Tutorials»
Представляем Вашему вниманию похожие книги на «Windows API Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Windows API Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.