Windows API Tutorials

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

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

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

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

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

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

Интервал:

Закладка:

Сделать

The constant, ID_MAIN, for instance, refers to the main program's icons (large and small in the same resource), the main menu, and the string with the Windows class name. ID_CAPTION refers to the window caption string. Such organization promotes code reusability, not to mention the ease of localization.

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

_set_new_handler (& NewHandler);

// Using exceptions here helps debugging your program

// and protects from unexpected incidents.

try {

// Create top window class

TopWinClass topWinClass (ID_MAIN, hInst, MainWndProc);

// Is there a running instance of this program?

HWND hwndOther = topWinClass.GetRunningWindow ();

if (hwndOther != 0) {

::SetForegroundWindow (hwndOther);

if (::IsIconic (hwndOther)) ::ShowWindow (hwndOther, SW_RESTORE);

return 0;

}

topWinClass.Register ();

// Create top window

ResString caption (hInst, ID_CAPTION);

TopWinMaker topWin (topWinClass, caption);

topWin.Create ();

topWin.Show (cmdShow);

// The main message loop

MSG msg;

int status;

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

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

::TranslateMessage (&msg);

::DispatchMessage (&msg);

}

return msg.wParam;

}

catch ( WinException e ) {

char buf [50];

wsprintf (buf, "%s, Error %d", e.GetMessage (), e.GetError ());

::MessageBox (0, buf, "Exception", MB_ICONEXCLAMATION | MB_OK);

}

catch (…) {

::MessageBox (0, "Unknown", "Exception", MB_ICONEXCLAMATION | MB_OK);

}

return 0;

}

Let's have a look at the WinClassclass. It encapsulates a Windows-defined structure called WNDCLASSEX and provides reasonable defaults for all its fields. It is derived from a simple WinSimpleClass class, which you might use to encapsulate some built-in Windows classes (like buttons, list views, etc.).

I have provided examples of methods that can be used to override the defaults. For instance, SetBgSysColorchanges the default background color of the user area of the window to one of the predefined system colors. The method SetResIconsloads appropriate icons from resources and attaches them to the window class. These icons will then appear in the upper left corner of the main window and on the windows' taskbar.

TopWinClassderived from WinClassmakes use of this method. It also assigns the menu to the top Window class.

class WinSimpleClass{

public:

WinSimpleClass (char const * name, HINSTANCE hInst) : _name (name), _hInstance (hInst) {}

WinSimpleClass (int resId, HINSTANCE hInst); char const * GetName () const {

return _name.c_str ();

}

HINSTANCE GetInstance () const {

return _hInstance;

}

HWND GetRunningWindow ();

protected:

HINSTANCE _hInstance;

std::string _name;

};

WinSimpleClass::WinSimpleClass(int resid, hinstance hinst) : _hInstance (hInst) {

ResString resStr (hInst, resId);

_name = resStr;

}

HWND WinSimpleClass::GetRunningWindow() {

HWND hwnd = :: FindWindow(getname (), 0);

if (:: IsWindow(hwnd)) {

HWND hwndPopup = :: GetLastActivePopup(hwnd);

if (:: IsWindow(hwndpopup)) hwnd = hwndPopup;

} else hwnd = 0;

return hwnd;

}

class WinClass: public WinSimpleClass{

public:

WinClass (char const * className, HINSTANCE hInst, WNDPROC wndProc);

WinClass (int resId, HINSTANCE hInst, WNDPROC wndProc);

void SetBgSysColor (int sysColor) {

_class.hbrBackground = reinterpret_cast (sysColor + 1);

}

void SetResIcons (int resId);

void Register ();

protected:

void SetDefaults ();

WNDCLASSEX_class;

};

WinClass::WinClass(char const * className, HINSTANCE hInst, WNDPROC wndProc) : WinSimpleClass (className, hInst) {

_class.lpfnWndProc = wndProc;

SetDefaults ();

}

WinClass::WinClass(int resId, HINSTANCE hInst, WNDPROC wndProc) : WinSimpleClass (resId, hInst) {

_class.lpfnWndProc = wndProc;

SetDefaults ();

}

void WinClass::SetDefaults() {

// Provide reasonable default values

_class.cbSize = sizeof (WNDCLASSEX);

_class.style = 0;

_class.lpszClassName = GetName ();

_class.hInstance = GetInstance ();

_class.hIcon = 0;

_class.hIconSm = 0;

_class.lpszMenuName = 0;

_class.cbClsExtra = 0;

_class.cbWndExtra = 0;

_class.hbrBackground = reinterpret_cast (COLOR_WINDOW + 1);

_class.hCursor = ::LoadCursor (0, IDC_ARROW);

}

void WinClass::SetResIcons(int resid) {

_class.hIcon = reinterpret_cast (

:: LoadImage(

_class.hInstance,

MAKEINTRESOURCE (resId),

IMAGE_ICON,

:: GetSystemMetrics(sm_cxicon),

:: GetSystemMetrics(sm_cyicon),

0));

// Small icon can be loaded from the same resource

_class.hIconSm = reinterpret_cast (

:: LoadImage(

_class.hInstance,

MAKEINTRESOURCE (resId),

IMAGE_ICON,

:: GetSystemMetrics(sm_cxsmicon),

:: GetSystemMetrics(sm_cysmicon),

0));

}

void WinClass::Register() {

if (:: RegisterClassEx(&_class) == 0) throw WinException ("Internal error: RegisterClassEx failed.");

}

class TopWinClass: public WinClass{

public:

TopWinClass (int resId, HINSTANCE hInst, WNDPROC wndProc);

};

TopWinClass::TopWinClass(int resId, HINSTANCE hInst, WNDPROC wndProc) : WinClass (resId, hInst, wndProc) {

SetResIcons (resId);

_class.lpszMenuName = MAKEINTRESOURCE (resId);

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

Интервал:

Закладка:

Сделать

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

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


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

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

x