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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
};
Finally, if your program needs colored pens on-demand, i.e., you can't possibly preallocate them for all the colors you'll need, you should use colored pens. When you define an automatic ColorPen object, its constructor both creates and attaches the pen. When the destructor is called, at the end of the scope, it detaches the pen and deletes it.
class ColorPen{
public:
ColorPen (HDC hdc, COLORREF color) : _hdc (hdc) {
_hPen = CreatePen(PS_SOLID, 0, color);
_hPenOld = (HPEN) SelectObject(_hdc, _hPen);
}
~ColorPen () {
SelectObject(_hdc, _hPenOld);
DeleteObject(_hPen);
}
private:
HDC _hdc;
HPEN _hPen;
HPEN _hPenOld;
};
You deal with Brushes in exactly the same way (there are, however, more types of brushes supported by Windows). For instance, here's a definition of a ColorBrush.
class ColorBrush{
public:
ColorBrush (HDC hdc, COLORREF color) : _hdc (hdc) {
_hBrush = CreateSolidBrush(color);
_hBrushOld = (HBRUSH) SelectObject(_hdc, _hBrush);
}
~ColorBrush () {
SelectObject(_hdc, _hBrushOld);
DeleteObject(_hBrush);
}
private:
HDC _hdc;
HBRUSH _hBrush;
HBRUSH _hBrushOld;
};
As always, you are encouraged to experiment on your own.
And now for something completely different: Threads
Using Threads
Multitasking is one of the most difficultaspects of programming. It makes it even more important to provide a simple set of abstractions and to encapsulate it in a nice object-oriented shell. In the OO world, the natural counterpart of the thread (which is a strictly procedural abstraction) is the Active Object. An active object owns a captive thread that performs certain tasks asynchronously. This thread has access to all the internal (private) data and methods of the object. The public interface of the Active Object is available to external agents (e.g., to the main thread, or to the Windows thread carrying messages) so that they, too, can manipulate the state of the object and that of the captive thread, albeit in a very controlled and restricted manner.
An Active Object is built upon a framework called ActiveObject. The implementor of the derived class is supposed to provide the implementation for the pure virtual methods InitThread , Run and Flush (as well as write the destructor).
class ActiveObject{
public:
ActiveObject ();
virtual ~ActiveObject () {}
void Kill ();
protected:
virtual void InitThread () = 0;
virtual void Run () = 0;
virtual void FlushThread () = 0;
static DWORD WINAPI ThreadEntry (void *pArg);
int _isDying;
Thread _thread;
};
The constructor of the ActiveObject initializes the captive thread by passing it a pointer to a function to be executed and a pointer to "this." We have to disable the warning about using "this" before it is fully constructed. We know that it won't be used too early, because the thread is created in the inactive state. The constructor of the derived class is supposed to call _thread.Resume() in order to activate it.
// The constructor of the derived class
// should call
// _thread.Resume ();
// at the end of construction
ActiveObject::ActiveObject() : _isDying (0),
#pragma warning(disable: 4355) // 'this' used before initialized
_thread (ThreadEntry, this)
#pragma warning(default: 4355)
{
}
The method Kill calls the virtual method FlushThread — it is supposed to release the thread from any wait state and let it run ahead to check the _isDying flag.
void ActiveObject::Kill() {
_isDying++;
FlushThread ();
// Let's make sure it's gone
_thread.WaitForDeath ();
}
We also have a framework for the ThreadEntry function (it's a static method of ActiveObject, so we can specify the calling convention required by the API). This function is executed by the captive thread. The argument it gets from the system is the one we passed to the constructor of the thread object — the "this" pointer of the Active Object. The API expects a void pointer, so we have to do an explicit cast to the ActiveObject pointer. Once we get hold of the Active Object, we call its pure virtual method InitThread, to make all the implementation specific preparations, and then call the main worker method, Run . The implementation of Run is left to the client of the framework.
DWORD WINAPI ActiveObject::ThreadEntry(void* pArg){
ActiveObject * pActive = (ActiveObject *) pArg;
pActive->InitThread ();
pActive->Run ();
return 0;
}
The Thread object is a thin encapsulation of the API. Notice the flag CREATE_SUSPENDEDwhich assures that the thread doesn't start executing before we are done with the construction of the ActiveObject .
class Thread{
public:
Thread ( DWORD (WINAPI * pFun) (void* arg), void* pArg) {
_handle = CreateThread(
0, // Security attributes
0, // Stack size
pFun, pArg, CREATE_SUSPENDED, &_tid);
}
~Thread () { CloseHandle(_handle); }
void Resume () { ResumeThread(_handle); }
void WaitForDeath () {
WaitForSingleObject(_handle, 2000);
}
private:
HANDLE _handle;
DWORD _tid; // thread id
};
Synchronization is what really makesmultitasking so hard. Let's start with mutual exclusion. Class Mutex is a thin encapsulation of the API. You embed Mutexes in your Active Object and then use them through Locks. A Lock is a clever object that you construct on the stack and for the duration of its lifetime your object is protected from any other threads. Class Lock is one of the applications of the Resource Management methodology. You have to put Locks inside all the methods of your Active Object that access data shared with the captive thread.
class Mutex{
friend class Lock;
public:
Mutex () { InitializeCriticalSection (& _critSection); }
~Mutex () { DeleteCriticalSection (& _critSection); }
private:
void Acquire () {
EnterCriticalSection(& _critSection);
Интервал:
Закладка:
Похожие книги на «Windows API Tutorials»
Представляем Вашему вниманию похожие книги на «Windows API Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «Windows API Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.