Windows API Tutorials

Здесь есть возможность читать онлайн «Windows API Tutorials» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Windows API Tutorials: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Windows API Tutorials»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Windows API Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Windows API Tutorials», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

}

class Controller{

public:

Controller(HWND hwnd, CREATESTRUCT * pCreate);

~Controller ();

void OnFolderChange (HWND hwnd, char const *folder);

private:

FolderWatcher _folderWatcher;

};

Now that we know how to deal with notification, let's have a look at their sources, the File Change Events. An event object is created by the file system in response to FindFirstChangeNotification. A handle to that event is returned from the call. We remember this handle and use it later to either renew or abandon our interest in further notifications. Notice that we can set the watch to be recursive, i.e., watching a given folder and all its subfolders and sub-subfolders. We can also express interest in particular types of changes by passing a bitwise OR of any combination of the following flags:

• FILE_NOTIFY_CHANGE_FILE_NAME (renaming, creating, or deleting a file)

• FILE_NOTIFY_CHANGE_DIR_NAME (creating or deleting a directory)

• FILE_NOTIFY_CHANGE_ATTRIBUTES

• FILE_NOTIFY_CHANGE_SIZE

• FILE_NOTIFY_CHANGE_LAST_WRITE (saving a file)

• FILE_NOTIFY_CHANGE_SECURITY

For convenience we have defined a few subclasses of FileChangeEvent that correspond to some useful combinations of these flags. One of them is the FolderChangeEvent that we used in our FolderWatcher.

class FileChangeEvent{

public:

FileChangeEvent (char const * folder, BOOL recursive, DWORD notifyFlags) {

_handle = FindFirstChangeNotification(folder, recursive, notifyFlags);

if (INVALID_HANDLE_VALUE == _handle) throw WinException ("Cannot create change notification handle");

}

~FileChangeEvent () {

if (INVALID_HANDLE_VALUE != _handle) FindCloseChangeNotification(_handle);

}

operator HANDLE () const { return _handle; }

BOOL ContinueNotification () {

return FindNextChangeNotification(_handle);

}

private:

HANDLE _handle;

};

class FolderChangeEvent: public FileChangeEvent{

public:

FolderChangeEvent (char const * folder) : FileChangeEvent (folder, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME) {}

};

class TreeChangeEvent: public FileChangeEvent{

public:

TreeChangeEvent (char const * root) : FileChangeEvent (root, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME) {}

};

It should be easy now to generalize this example to do some really useful work in your programs. Remember to look up the API's that we use in these tutorials in the online help that comes with your compiler.

How about some OLE or COM programming without MFC? Go to the next page.

Using Windows95 Shell and COM — A. K. A. OLE

COM programming is so difficultthat you shouldn't even try it without MFC. Right or wrong? Absolutely wrong!. Granted, OLE and its successor COM have the elegance of a figure-skating hippopotamus. But putting MFC on top of COM is like dressing the hippo in an oversized clown suit.

So what is a programmer to do when faced with the necessity to use some of the Windows 95 (and Windows NT 4.0) shell features that are only accessible through COM interfaces? Read on…

To begin with, whenever you are planning to use COM, you have to tell the system to initialize the COM subsystem. Similarly, whenever you're done using COM, you should tell the system to uninitialize it. The simplest thing to do, is to define an object whose constructor initializes COM and whose destructor deinitializes it. The best place to place it is to embed it in the Controller object (see the GenericWindows program), like this.

class Controller{

public:

Controller (HWND hwnd, CREATESTRUCT * pCreate);

~Controller ();

// ...

private:

UseCom _comUser;// I'm a COM user

Model _model;

View _view;

HINSTANCE _hInst;

};

This way we are guaranteed that the COM subsystem will be initialized before any calls are made to it and that it will be deinitialized after the program has done its tear-down (i.e., after the View and the Model have been destroyed).

The UseCom class is very simple.

class UseCom{

public:

UseCom () {

HRESULT err = CoInitialize(0);

if (err != S_OK) throw "Couldn't initialize COM";

}

~UseCom () {

CoUninitialize();

}

};

So far it hasn't been too difficult, has it? That's because we haven't touched the bane of COM programming — reference counting. You see, every time you obtain an interface, its reference count is incremented, every time you're done with it, you are supposed to explicitly decrement it. Oh, and it gets even weirder when you start querying, cloning, passing interfaces around, etc. But wait a moment, we know how to manage such problems! It's called Resource Management. We should never touch COM interfaces without encapsulating them in smart interface pointers. Here's how it works.

template class SIfacePtr{

public:

~SIfacePtr () {

Free ();

}

T * operator->() { return _p; }

T const * operator->() const { return _p; }

operator T const * () const { return _p; }

T const & GetAccess () const { return *_p; }

protected:

SIfacePtr () : _p (0) {}

void Free () {

if (_p != 0) _p-> Release();

_p = 0;

}

T * _p;

private:

SIfacePtr (SIfacePtr const & p) {}

void operator = (SIfacePtr const & p) {}

};

Don't worry that this class looks unusable (because it has a protected constructor). We'll never use it directly — we'll inherit from it. By the way, this is a great trick: create a class with a protected do-nothing constructor and keep deriving from it. All the derived classes will have to provide their own specialized public constructors. As you might have guessed, various classes derived from SIfacePtr will differ in the way they obtain, in their constructors, the interface in question.

Private dummy copy constructor and operator= are not strictly necessary, but they will save you hours of debugging if, by mistake, you'll pass a smart interface by value rather than by reference. That's a big no-no. You'll end up releasing the same interface twice and that'll screw the COM's reference counting. Believe me, I've been there. As it is, the compiler will refuse to pass by value an object that has a private copy constructor (dummy or not). It will also issue an error when you try to assign an object that has a private assignment operator.

To wrap this short introduction up, let me present one more variation on the theme of smart pointers. Shell API's often allocate memory using their own special allocator. That wouldn't be so bad, if it weren't for the fact that they expect you to release this memory using the same allocator. So, whenever the shell hands us such an embarassing package, we'll wrap it up in a special smart pointer.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Windows API Tutorials»

Представляем Вашему вниманию похожие книги на «Windows API Tutorials» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Windows API Tutorials»

Обсуждение, отзывы о книге «Windows API Tutorials» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x