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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
CW_USEDEFAULT, // y position
CW_USEDEFAULT, // witdh
CW_USEDEFAULT, // height
0, // handle to parent window
0, // handle to menu
hInstance, // application instance
0); // window creation data
}
A Windows program is event-driven. It means that you, as a programmer, are supposed to be on the defensive. the user will bombard windows with various input actions, and windows will bombard your program with messages corresponding to these actions. All you have to do is to respond to these messages. The picture below shows schematically how it works.
Windows gets various events from the keyboard, the mouse, the ports, etc. Each event is quickly converted into a message. Windows dispatches messages to appropriate windows. For instance, all keyboard messages go to the window that currently has the input focus(the active window). Mouse messages are dispatched according to the position of the mouse cursor. They usually go to the window that is directly under the cursor (unless some program captured the mouse).
All these messages end up in message queues. Windows keeps a message queue for every running application (actually, for every thread). It is your duty to retrieve these messages one-by-one in what is called a message loop. Your program has to call GetMessageto retrieve a message. then you call DispatchMessageto give it back to windows. couldn't windows just go ahead and dispatch all these messages itself? in principle it could, but a message loop gives your program a chance to have a peek at them and maybe perform some additional actions before dispatching them. or not…
Each message is addressed to a particular window. When you tell Windows to dispatch such a message, it will figure out the class of this window, find the associated Window Procedure, and call it. Every single message sent to our window will end up in our window procedure. It is now up to us to react to it. So, do we have to respond appropriately to every possible type of Windows message? There a hundreds of them! Fortunately, no! We only need to intercept these messages that we are interested in. Everything else we pass back to Windows for default processing using DefWindowProc.
Let's have a look at WinMain. the execution of a windows program doesn't start in main-it starts in WinMain. First, we create a winclass and register it. Then we create an actual window (of the class we've just registered) and show it. Actually, WinMainis called with the appropriate show directive — the user might want to start the application minimized or maximized. So we just follow this directive. Next we enter the message loop and keep retrieving and dispatching messages until GetMessagereturns 0. at that point the message's wparam will contain the return code of the whole program.
int WINAPI WinMain(hinstance hinst, hinstance hprevinst, char * cmdParam, int cmdShow) {
char className [] = "Winnie";
WinClass winClass (WindowProcedure, className, hInst);
winClass.Register ();
WinMaker win ("Hello Windows!", className, hInst);
win.Show (cmdShow);
MSG msg;
int status;
while ((status = :: GetMessage(& msg, 0, 0, 0)) != 0) {
if (status == –1) return –1;
:: DispatchMessage(& msg);
}
return msg.wParam;
}
The GetMessageAPI is an interesting example of the bizarre microsoft Troolean (as opposed to traditional, Boolean ) logic. GetMessageis defined to return a bool, but the documentation specifies three types of returns, non-zero, zero and –1. I am not making it up! here's an excerpt from the help file:
• If the function retrieves a message other than WM_QUIT, the return value is nonzero.
• If the function retrieves the WM_QUIT message, the return value is zero.
• If there is an error, the return value is -1.
The other part of a Windows program is the Windows Procedure. Remember, Windows will call it with all kinds of messages. All these messages can be ignored by sending them to DefWindowProc. There is only one message that we must intercept. That's the WM_DESTROY message that is sent by Windows when the user decides to close the window (by pressing the close button in the title bar). The standard response to WM_DESTROY is to post the quit message and return zero. That's all there is to it.
// Window Procedure called by Windows
LRESULT CALLBACK WindowProcedure(HWND hwnd, unsigned int message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_DESTROY:
:: PostQuitMessage(0);
return 0;
}
return :: DefWindowProc(hwnd, message, wParam, lParam);
}
This is actually the ugliest, least object oriented part of encapsulating Windows. It's getting better from this point on. Like in this genericWindows program.
The Generic Windows Program
This program uses the basic set of classes that encapsulate the Windows API.
• Controller — The bridge between Window Procedure and Object Oriented world.
• View — Encapsulates the output of a Windows program.
• Canvas — Encapsulated various Device Contexts and things you can do with them.
• Model — The worker and the brain of your program. Doesn't deal with Windows at all.
Note: This is a Win32 program — it will run under Windows 95 and Windows NT.
Note: _set_new_handleris Microsoft-specific. If you're using some other compiler, just remove this line of code. According to current C++ standard, operator new should throw exceptions anyway.
Note: Older compilers might have problems with templates. In such case, you may substitute the use of Win[Get/Set]Longtemplates with direct calls to Get/SetWindowLong. For instance, instead of calling:
Controller * pCtrl = WinGetLong (hwnd);
you can call:
Controller * pCtrl = reinterpret_cast (::GetWindowLong (hwnd, GWL_USERDATA));
Let's start with WinMainwhere we create the window class and the top window of our application. i have encapsulated these actions inside two classes: WinClassand WinMaker. WinClass can also tell us if there already are running instances of our program. When something like that happens, in our example, we will simply activate the previously running instance of the program and exit. You should do that when you want only one instance of your program running at a time.
Once the top window is successfully created, we enter the message loop. Notice that this time we are processing keyboard shortcuts by calling TranslateMessage. That's because our program has menu items that can be accessed using Alt+key combinations.
Another interesting twist in this program is that we are no longer using strings to name our resources — we use numerical ids. More than that-even when the API's call for strings, like the name of the Windows class or the caption, we store the strings in string resources and access them through ids. Your Windows development environment most likely has a resource editor that lets you create icons, menus, and string resources and assign them appropriate numerical ids. Symbolic names for these ids are stored in a header file produced by such an editor — in our case it's called resource.h .
Читать дальшеИнтервал:
Закладка:
Похожие книги на «Windows API Tutorials»
Представляем Вашему вниманию похожие книги на «Windows API Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Windows API Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.