Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

class DispObject: public CoObject{

public:

DispObject(CLSID const & classId) :_iDisp (0) {

HRESULT hr = :: CoCreateInstance( classId, 0, CLSCTX_ALL, IID_IDispatch, (void**)&_iDisp);

if (FAILED (hr)) {

if (hr == E_NOINTERFACE) throw "No IDispatch interface";

else throw HEx (hr, "Couldn't create DispObject");

}

}

~DispObject() {

if (_iDisp) _iDisp->Release ();

}

operator bool () const {

return _iDisp != 0;

}

bool operator ! () const {

return _iDisp == 0;

}

DISPID GetDispId(WCHAR * funName) {

DISPID dispid;

HRESULT hr = _iDisp->GetIDsOfNames ( IID_NULL, &funName, 1, GetUserDefaultLCID (), &dispid);

return dispid;

}

void GetProperty(DISPID propId, VARIANT & result) {

// In parameters DISPPARAMS args = { 0, 0, 0, 0 };

EXCEPINFO except;

UINT argErr;

HRESULT hr = _iDisp->Invoke (propId, IID_NULL, GetUserDefaultLCID (), DISPATCH_PROPERTYGET, &args, &result, &except, &argErr);

if (FAILED (hr)) throw HEx (hr, "Couldn't get property");

}

void * AcquireInterface(IID const & iid) {

void * p = 0;

HRESULT hr = _iDisp->QueryInterface (iid, &p);

if (FAILED (hr)) {

if (hr == E_NOINTERFACE) throw "No such interface";

else throw HEx (hr, "Couldn't query interface");

}

return p;

}

protected:

DispObject (IDispatch * iDisp) : _iDisp (iDisp) {}

DispObject () : _iDisp (0) {}

protected:

IDispatch * _iDisp;

};

Below is a small illustration of dynamic dispatching. Of course, the same result could have been obtained directly by calling the method get_Name of the IGenericDocument interface. We'll use this direct (vtable) method in a moment to obtain the full path of the document.

// Use docObj as a dispatch interface

DISPID pid = docObj. GetDispId(L"Name");

VARIANT varResult ;

:: VariantInit(& varResult) ;

docObj. GetProperty(pid, varResult);

BString bName (varResult);

CString cName (bName);

canvas.Text (20, y, "Name:");

canvas.Text (200, y, cName);

And this is how you obtain the path, the vtable way.

SObjFace doc (docObj);

BStringbPath;

doc->get_FullName (bPath.GetPointer ());

Now you shouldn't have any problems understanding the code that retrieves the line number of the line where the user positioned the cursor.

BString bType;

doc->get_Type (bType.GetPointer ());

if (type.IsEqual ("Text")) {

SObjFace text (docObj);

SSelectionselObj (text);

SObjFace sel (selObj);

long line;

sel->get_CurrentLine (&line);

canvas.Text (20, y, "CurrentLine:");

char buf [10];

wsprintf (buf, "%ld", line);

canvas.Text (200, y, buf);

}

SSelection is a DispObject that can be obtained by calling a method get_Selection of the text document interface.

class SSelection: public DispObject{

public:

SSelection(SObjFace & doc) {

HRESULT hr = doc->get_Selection (& _iDisp);

if (FAILED (hr)) throw HEx (hr, "get_Selection failed");

}

};

You might be a little confused if this is your first contact with OLE (an understatement!). So here is a summary of what the various actions are that have to be done in order to accomplish a simple Automation task. Notice, this is the client side of the equation. If you want your application to be an Automation server, things are a bit more complicated. Fortunately, there is more literature about it.

So here's what you have to do.

The research. Search your registry (using RegEdt32 or OLE/COM object viewer) to find the ProgID of the application you want to get hold of. HKEY_CLASSES_ROOT is the starting point. You'll see there such keys as Word.Application, Excel.Application and many others. Find the Type Libraries using OLE/COM object viewer. They will have the class ids and interface ids that you have to copy and paste into your code. Find the header files for these interfaces. In your program: Convert ProgID to class id. To connect to a running app or to activate a new one, create SObject using the ClassID. Obtain the IApplication interface from the object (use the IObjFace template). Use this interface to get hold of other objects internal to the application. For each such object: Declare a class derived from DispObject In its constructor use the appropriate get_* method to get access to the internal object. Create an object of this class, passing it the interface of the parent object. Obtain the appropriate interface from this object by instantiating the template IObjFace . Call appropriate methods of this interface.

So what was this big deal with reference counting in OLE? Beats me! It must have disappeared, once we started using the correct encapsulation. Below is a diagram of class dependencies. OLE objects on the left, OLE interfaces on the right.

At runtime, you start with the SObject that represents the program you're connecting to and then keep going from object to interface and from interface to DispObject. You use objects as sources of interfaces and interfaces for calling specific methods and obtaining other objects.

Splitter Bar

A splitter bar is a useful control that is not part of the Windows' common bag of controls. How difficult is it to implement it? Not so difficult, as it turns out, once you know the basics of Windows API. The description that follows might seem complicated at first, but you'll be learning several very important techniques that can be used over and over in a variety of situations. Working with child windows, mouse capture, drawing using xor mode, just to mention a few.

A splitter bar is a window. More precisely, it's a child window. It is positioned between two other child windows — we'll call these left and right panes, respectively (or top and bottom, for a horizontal splitter). There must also be a main window that fathers the three children.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x