Brook Miles - theForger's Win32 API Tutorial

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

theForger's Win32 API Tutorial: краткое содержание, описание и аннотация

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

Visit
Software! Code North
This tutorial attempts to get you started developing with the Win32 API as quickly and clearly as possible. It's meant to be read as a whole You may use this tutorial for absolutely no charge, however there are costs associated with hosting it on the web. If you found it to be of use to you and want to give something back, I would be grateful for donations of any amount to help pay for this website. This page gets approximately 11 thousand hits a month, and it adds up after a while :)
Enjoy the tutorial,
Brook
I would like to thank the following for the contributions they've made: Yih Horng, Todd Troxell, T Frank Zvovushe, Suzanne Lorrin, Seth McCarus, Crispina Chong, John Crutchfield, Scott Johnstone, Patrick Sears. As well as those who have simply written to say they've found the tutorial useful. It's much appreciated!
Welcome to Version 2.0 of theForger's Win32 API Tutorial

theForger's Win32 API Tutorial — читать онлайн бесплатно полную книгу (весь текст) целиком

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

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

Интервал:

Закладка:

Сделать

NOTE:MSDN states the following for the lStructSize member:

lStructSize

Specifies the length, in bytes, of the structure.

Windows NT 4.0:In an application that is compiled with WINVER and _WIN32_WINNT>= 0x0500, use OPENFILENAME_SIZE_VERSION_400 for this member.

Windows 2000/XP:use sizeof(OPENFILENAME) for this parameter.

Basically what this means is that as of Windows 2000 they added some members to this struct, and so it's size changed. If the code above doesn't work for you it's possibly because the size that your compiler used and the size that your operating system (ie. Windows 98, Windows NT4) expected were different and so the call failed. If this happens, try using OPENFILENAME_SIZE_VERSION_400 instead of sizeof(ofn) . Thanks to people that pointed this out to me.

Reading and Writing Files

In windows you have a few options as to how you want to access files. You can use the old io.h open() / read() / write() , you can use stdio.h fopen() / fread() / fwrite() , and if you are in C++ use can use iostreams.

However in windows all of these method ultimately call the Win32 API functions, which are what I will use here. If you are already comfortable using file IO with another method it should be fairly easy to pick up, or if you want simply use your method of choice to access files.

To open files, you can use OpenFile() or CreateFile() . MS recommends using only CreateFile() as OpenFile() is now "obsolete". CreateFile() is a much more versatile function and provides a great deal of control over the way you open files.

Reading

Say for example you have allowed the user to select a file using GetOpenFileName()…

BOOL LoadTextFileToEdit(HWND hEdit, LPCTSTR pszFileName) {

HANDLE hFile;

BOOL bSuccess = FALSE;

hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

if (hFile != INVALID_HANDLE_VALUE) {

DWORD dwFileSize;

dwFileSize = GetFileSize(hFile, NULL);

if (dwFileSize != 0xFFFFFFFF) {

LPSTR pszFileText;

pszFileText = GlobalAlloc(GPTR, dwFileSize + 1);

if (pszFileText != NULL) {

DWORD dwRead;

if (ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)) {

pszFileText[dwFileSize] = 0; // Add null terminator

if (SetWindowText(hEdit, pszFileText)) bSuccess = TRUE; // It worked!

}

GlobalFree(pszFileText);

}

}

CloseHandle(hFile);

}

return bSuccess;

}

There is a complete function to read a text file into an edit control. It takes as paramters the handle to the edit control and the name of the file to read in. This perticular function has a fair bit of error checking, file IO is one place where a lot of things can go wrong, and so you need to be on the lookout for errors.

Notethe variable dwRead . We don't use it except as a paramter in ReadFile() . This parameter MUST be provided, the call will fail without it.

In the call to CreateFile()GENERIC_READ means we only want read access. FILE_SHARE_READ means it's okay if other programs open the file at the same time we do, but ONLY if they want to read as well, we don't want them writing to the file while we are reading it. And OPEN_EXISTING means only open the file if it already exists, don't create it, and don't overwrite it.

Once we've opened the file and chacked to see that CreateFile() succeeded, we check the size of the file so we'll know how much memory we need to allocate in order to read the entire thing. We then allocate the memory, check to make sure the allocation succeeded, and then call ReadFile() to load the contents from disk into our memory buffer. The API file functions have no concept of Text Files so they won't do things like read a single line of text, or add NULL terminators to the end of our strings. This is why we've allocated an extra byte and after we read in the file we add the NULL ourselves so that we can then pass the memory buffer as a string to SetWindowText() .

Once all that has succeeded we set out success variable to TRUE , and clean up as we reach the end of the function, freeing the memory buffer and closing the file handle before finally returning to the caller. Writing

BOOL SaveTextFileFromEdit(HWND hEdit, LPCTSTR pszFileName) {

HANDLE hFile;

BOOL bSuccess = FALSE;

hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

if (hFile != INVALID_HANDLE_VALUE) {

DWORD dwTextLength;

dwTextLength = GetWindowTextLength(hEdit);

// No need to bother if there's no text.

if (dwTextLength> 0) {

LPSTR pszText;

DWORD dwBufferSize = dwTextLength + 1;

pszText = GlobalAlloc(GPTR, dwBufferSize);

if (pszText != NULL) {

if (GetWindowText(hEdit, pszText, dwBufferSize)) {

DWORD dwWritten;

if (WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL)) bSuccess = TRUE;

}

GlobalFree(pszText);

}

}

CloseHandle(hFile);

}

return bSuccess;

}

Very similar to reading files, the function to write files has a few changes. First of all when we call CreateFile() we specify that we want Read access, that the file should always be created new (and if it exists it will be erased as it's opened) and that if it doesn't exist, it will be created with the normal file attributes.

Next we get the length of the memory buffer needed from the edit control, since this is the source of the data. Once we've allocated the memory, we request the string from the edit control using GetWindowText() and then write it to the file with WriteFile() . Again, like with ReadFile() the parameter that returns how much was actually written is required, even though we don't use it.

App Part 3: Tool and Status bars

Example: app_three

An IMPORTANT Word on Common Controls

As with all common controls, you must call InitCommonControls() BEFORE you try and use them. You will need to #include in order to use this function and to get the functions and declarations necessary for use of the Common Controls. You will also need to add comctl32.lib to your linker settings if it is not already there. Note that InitCommonControls() is an older API, and for more control you can use InitCommonControlsEx() (aka InitCommonControlSex() ) which is also required for the most recent common controls. However since I'm not using any of the advanced features, InitCommonControls() is adequate and simpler.

Toolbars

You can create a toolbar using CreateToolbarEx() but I'm not going to, so there. First thing you need to do is actually create the toolbar…

hTool = CreateWindowEx(0, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hwnd, (HMENU)IDC_MAIN_TOOL, GetModuleHandle(NULL), NULL);

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

Интервал:

Закладка:

Сделать

Похожие книги на «theForger's Win32 API Tutorial»

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


Отзывы о книге «theForger's Win32 API Tutorial»

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

x