Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

class Canvas{

public:

operator HDC () { return _hdc; }

void Line ( int x1, int y1, int x2, int y2 ) {

:: MoveToEx(_hdc, x1, y1, 0);

:: LineTo(_hdc, x2, y2);

}

void Text (int x, int y, char const * buf, int cBuf) {

:: TextOut( _hdc, x, y, buf, cBuf );

}

void Char (int x, int y, char c) {

:: TextOut(_hdc, x, y, & c, 1);

}

protected:

// Protected constructor: You can't construct

// a Canvas object, but you may be able

// to construct objects derived from it.

Canvas (HDC hdc): _hdc (hdc) {}

HDC _hdc;

};

The canvas that you create in response to WM_PAINT message are of special kind. They obtain the device context by calling BeginPaintand release it by calling EndPaint. paintstruct contains additional information about which parts of the user area should be painted, etc. For now we ignore such details, but if you're serious about performance, you should learn more about it.

// Concrete example of canvas.

// Create this object after WM_PAINT message

class PaintCanvas: public Canvas{

public:

// Constructor obtains the DC

PaintCanvas (HWND hwnd) : Canvas (:: BeginPaint(hwnd, & _paint)), _hwnd (hwnd) {}

// Destructor releases the DC

~PaintCanvas () {

:: EndPaint(_hwnd, & _paint);

}

protected:

PAINTSTRUCT _paint;

HWND _hwnd;

};

What would Windows programming be without controls?

Windows Controls

Controls can be added to the main window or to any dialog box in your program. Controls are best picked and positioned using a graphical resource editor. Such an editor will also let you pick names or symbolic id's for your controls. You will then use these id's to identify the controls in your program.

Most controls can be encapsulated in objects that are either embedded in the appropriate Controller (you can have a separate Controller objects for every dialog box in your program) or, for static controls, in the View.

Controller objects are created in response to WM_CREATE or, for dialog boxes, WM_INITDIALOG messages. Constructors of controls embedded in these Controllers are executed at that time.

The base class for most controls is SimpleControl. It obtains and stores the window handle of the particular control. To obtain this handle, you need the parent window handle and the control's id.

class SimpleControl{

public:

SimpleControl (HWND hwndParent, int id) : _hWnd ( GetDlgItem(hwndparent, id)) {}

void SetFocus () {

::SetFocus(_hwnd);

}

HWND Hwnd () const { return _hWnd; }

protected:

HWND _hWnd;

};

Here's an example of an edit control

class Edit: public SimpleControl{

public:

Edit (HWND hwndParent, int id) : SimpleControl (hwndParent, id) {}

void SetString (char* buf) {

SendMessage(Hwnd (), WM_SETTEXT, 0, (LPARAM) buf);

}

// code is the HIWORD (wParam)

static BOOL IsChanged (int code) {

return code == EN_CHANGE;

}

int GetLen () {

return SendMessage(Hwnd (), WM_GETTEXTLENGTH, 0, 0);

}

void GetString (char* buf, int len) {

SendMessage(Hwnd (), WM_GETTEXT, (WPARAM) len, (LPARAM) buf);

}

void Select () {

SendMessage(Hwnd (), EM_SETSEL, 0, –1);

}

};

This is how the edit control may be used:

class Controller{

public:

Controller(HWND hwnd);

private:

Edit _edit;

char _string [maxLen];

};

Controller::Controller(hwnd hwnd) : _edit (hwnd, IDC_EDIT) {

_edit.SetFocus ();

}

void Controller::Command(HWND hwnd, WPARAM wParam, LPARAM lParam) {

switch (LOWORD(wParam)) {

case IDC_EDIT:

if (_edit.IsChanged(HIWORD (wParam))) {

_edit.GetString (_string, maxLen);

}

break;

}

}

But, of course, the most likely place to use controls is in a Dialog Box.

Program with a Dialog Box as the Main Window

The main window of a program doesn't have to be a resizable general purpose window. many small applications work better in a dialog box format. The obvious advantage of such an approach is that you can use a resource editor to arrange all your controls on the surface of the box. This is in fact how the UI of the Frequency Analyzer was implemented. Since this is a useful technique, i will describe it in some detail.

First of all, we have to design the dialog box using the resource editor. We assign identifiers to all the controls and to the dialog itself. Here, the dialog resource has the identifier DLG_MAIN. In the WinMain procedure we don't have to register any window class, because Windows has a pre-defined class for dialog boxes. Instead of creating a window, we call CreateDialog , passing it a pointer to our own dialog procedure (explained later).

The message loop is non-standard in that it calls IsDialogMessage for every message. This API not only checks whether a given message is directed at the dialog box, but more importantly, it dispatches it to the dialog procedure. If the message was not for the dialog, we do the standard translation and dispatching.

For convenience, we keep the value of HINSTANCE in a global variable. This is actually a precursor of a more general object — the Application. Here, however, we decided it was too trivial to deserve a class of its own.

HINSTANCE TheInstance = 0;

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, char * cmdParam, int cmdShow) {

TheInstance = hInst;

_set_new_handler (& NewHandler);

HWND hDialog = 0;

hDialog = CreateDialog(hinst, MAKEINTRESOURCE(dlg_main), 0, DialogProc);

if (!hDialog) {

char buf [100];

wsprintf (buf, "Error x%x", GetLastError ());

MessageBox(0, buf, "CreateDialog", MB_ICONEXCLAMATION | MB_OK);

return 1;

}

MSG msg;

int status;

while ((status = GetMessage(& msg, 0, 0, 0)) != 0) {

if (status == –1) return –1;

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

Интервал:

Закладка:

Сделать

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

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


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

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

x