Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 15

Міністерство освіти та науки України

Національний університет “Львівська політехніка”


Інститут комп’ютерних наук та інформаційних технологій
Кафедра автоматизованих систем управління

ПРОГРАМУВАННЯ ЗА ДОПОМОГОЮ ФУНКЦІЙ


WINDOWS API
ЗБІРНИК ЛАБОРАТОРНИХ РОБІТ

Методичні вказівки
до курсу “Операційні системи”
для студентів базової вищої освіти
за напрямком “Комп’ютерні науки”

Львів - 2022
Laboratory work #11

Topic – Specialized folders and methods of listing and


searching for system objects.
The goal is to gain experience in building software
systems to improve their structuring and diagnostics.
THEORETICAL PROVISIONS
An operating system is an environment for the
"coexistence" of many programs that interact with each other
and use common resources. In order to avoid conflicts between
programs, save correct system settings and better structure it,
WINDOWS developers introduced a special database called
the registry. The registry is stored in hidden system files
user.dat and system.dat. In almost half of the cases, the failure
of the operating system is associated with incorrect information
in these files.
The registry resembles a tree of directories, each of which
is called a key. Each program can write something to the
registry or read some information from it. This is convenient
for using shared data for multiple applications. In addition, for
each registry key, the time it was created is stored. This makes
it possible to make commercial versions of programs that are
designed for different working hours at different cost in
payment. For example, the program may stop working if the
current time differs from the time of the generated key by more
than a month, or a day, or a year.
In addition, the registry can store information about
previous program launches to determine the optimal mode of
its operation, or save certain individual user settings to make
the program more convenient and efficient for him.
The registry also defines the names of so-called
specialized folders, each of which contains files of a certain
type or is used for a certain purpose. Sometimes the contents of
these folders can be displayed as a menu made up of shortcuts.
A standard internal index is attached to each such specialized
folder, which is repeated from one version of the system to
another and is denoted by a standard constant. Below are some
specialized folders, as well as their indexes. In this laboratory
work, it will be necessary to obtain a list of registry values of a
given key and a list of specialized folders, to learn how to
create and delete registry keys.

Param. Name Value Comments


CSIDL_DESKTOP 0 Desktop folder
CSIDL_PROGRAMS 2 Program Files folder
CSIDL_PRINTERS 4 Installed printers
CSIDL_PERSONAL 5 My Documents folder
CSIDL_FAVORITES 6 My Favorites folder
CSIDL_STARTUP 7 Startup (Autorun) folder
CSIDL_RECENT 8 Recently used Documents
CSIDL_SENDTO 9 SendTo menu item
CSIDL_STARTMENU 0bh StartMenu folder
CSIDL_NETHOOD 13h Network neighborhood
CSIDL_FONTS 14h Installed Fonts
CSIDL_TEMPLATES 15h Templates for different documents
CSIDL_APPDATA 1ah Program working directory
CSIDL_INTERNET 20h Temporary Internet Files
CSIDL_COOKIES 21h Personalization for viewing sites
CSIDL_HISTORY 22h System report for user

You can get the name of the specialized folder in 2 steps:


1. Get the handle of the specialized folder using the
SHGetSpecialFolderLocation function using the constant
given in the table.
2. Get the full path to the folder using the
SHGetPathFromIDList function through its handle.

A folder handle is actually a packed form of parent folder


numbers up to the top level. Since after deleting files in the
directory, records about them remain in their places, and only
deletion marks are placed, so these numbers do not change
until the end of the system's existence. It can be said that the
sequence of folder numbers is a rather concise form of
representing the path to the desired folder, which is used by
other functions, for example, SHBrowseForFolder.

The program for finding the names of


specialized folders by index is shown below:

.586
.model flat,STDCALL
extrn SHGetSpecialFolderLocation:Proc
extrn MessageBoxA:Proc
extrn ExitProcess:Proc
extrn SHGetPathFromIDList:Proc
.data
INDEX dd 0 ; index of the folder
DIRECTORY_ID dd 0 ; handle of the folder
DIRECTORY_NAME db 512 dup(0) ; Folder path
T db ' Cпеціальна папка:',0
.code
Start: push offset DIRECTORY_ID ; The result of function
push INDEX ; input folder index
push 0 ; not used
call SHGetSpecialFolderLocation
inc INDEX
cmp INDEX,65 ; index to be less than 65
jnc STOP
push offset DIRECTORY_NAME ; Result: folder name and path
push DIRECTORY_ID ; handle of folder (see function before)
call SHGetPathFromIDList
; Output the Special Folder path and name:
call MessageBoxA,0,offset DIRECTORY_NAME,offset T,1
cmp eax,1
jz Start
STOP: call ExitProcess,0
end Start

The folder selection function also outputs the result in the


form of packed numbers. In order to use it, it is necessary to
enter the following fragment immediately after the line call
SHGetSpecialFolderLocation:
;----------------------------------------------------------
Extrn SHBrowseForFolder:Proc
.data
BROWSEINFO:
hwndOwner dd 0
DIRECTORY_ID dd 0 ; handle of the folder
pszDisplayName dd 0
lpszTitle dd offset T
ulFlags dd 08075h
lpfn dd 0
lParam dd 0
iImage dd 0
.code
call SHBrowseForFolder,offset BROWSEINFO
mov DIRECTORY_ID,eax
;--------------------------------------------------------
The variable DIRECTORY_ID has already been declared
before, and in order for it not to be duplicated, it must be
removed from the previous fragment of the data segment.
You can search for the desired objects in the operating
system in another way. For example, there are special list
functions that allow you to enumerate some system objects, for
example, windows, registry keys, network connections, etc.
The word "Enum" (from the English word enumerate) is
included in the names of such functions. During the operation
of such functions, the system finds the handle of the object to
be sorted (enumerated) and passes it to a special callback
procedure, which must be written by the user of the function.
Such a call to a system function, which in turn calls a user
subroutine, is called callback technology (from the English
word callback). So, the callback procedure receives a handle to
the object as a parameter when accessing it.
In the callback procedure, the user can use arbitrary
functions to obtain additional information about the object, or
change the parameters of the object itself, for example, by
sending appropriate messages to it.
Функція Функція знаходить:
EnumWindows всі вікна верхнього рівня в системі
RegEnumKeyExA всі підключі (subkeys) відкритого ключа реєстру
RegEnumValueA всі значення відкритого ключа реєстру
EnumResourceTypesA всі типи ресурсів даної програми
WnetEnumResourceA всі мережні ресурси, що доступні користувачеві
NetConnectionEnum всі мережні з’єднання користувача
NetFileEnum всі відкриті файли на сервері
NetGroupEnum всі групи користувачів
NetScheduleJobEnum всі завдання, що виконуються на комп’ютері
NetServerDiskEnum всі диски на віддаленому комп’ютері
NetServerEnum всі сервери на віддаленому комп’ютері
NetUserEnum всі рахунки користувачів на сервері
NetWkstaUserEnum всі імена користувачів
RasEnumConnectionsA всі з’єднання віддаленого доступу до комп’ютера
EnumProtocolsA всі встановлені протоколи передачі даних
EnumPrintersA всі локальні та віддалені принтери
EnumEnhMetaFile всі типи даних у заданому метафайлі
EnumFontsA всі шрифти на певному пристрої та в системі
EnumObjects всі об’єкти графічного контексту вікна
AcmDriverEnum всі драйвери для аудіо компресії
AcmFormatEnumA всі формати файлів для даного драйвера
EnumChildWindows всі дочірні вікна для заданого вікна
EnumClipboardFormats всі типи даних, що знаходяться в буфері обміну
EnumDesktopWindows всі вікна Робочого столу
EnumDesktopsA всі робочі столи, які є на комп’ютері
EnumDisplaySettingsA всі режими роботи дисплея
EnumThreadWindows всі батьківські вікна заданого процесу
EnumWindowStationsA всі робочі станції на даному комп’ютері

Consider the EnumWindows search function for all open


windows, which uses the callback principle. To do this, you
need to create a new text document and enter the following
program into it:

.586
.model flat,STDCALL
extrn ExitProcess:Proc, MessageBoxA:Proc
extrn EnumWindows:Proc
extrn GetWindowTextA:Proc, SendMessageA:Proc
MB_YESNOCANCEL equ 3h
IDCANCEL equ 2
IDYES equ 6
IDNO equ 7
WM_CLOSE equ 10h
.data
TITLE1 db 'Keep this window open?',0
WND_NAME db 200 dup(0)
;===============================
.code
Start: push 0 ; not used
push offset PROG1 ; CallBack-function address;
call EnumWindows
STOP: call ExitProcess,0
;======================== Procedure of CallBack:

PROG1 proc hwnd:DWORD, wparam:DWORD


push 200 ; maxima size
push offset WND_NAME ; addr of window name;
push hwnd ; handle of window;
call GetWindowTextA ; API call;
cmp byte ptr WND_NAME,0 ; skip all windows without name
jz CONT_ENUM1
call MessageBoxA,0,offset WND_NAME,offset TITLE1,
MB_YESNOCANCEL
cmp eax,IDCANCEL
jz STOP_ENUM
cmp eax,IDYES
jz CONT_ENUM1

cmp eax,IDNO
jnz STOP_ENUM
; If pressed «NO», the window will close:
call SendMessageA,hwnd, WM_CLOSE,0,0
jmp CONT_ENUM1
STOP_ENUM:
xor eax,eax ; eax = 0 – finish enumeration.
jmp EX_PROG1
CONT_ENUM1: ; eax = 1 – continue enumeration
mov eax,1
EX_PROG1:
Ret ; Return from Callback to EnumWindows.
Endp PROG1
End Start

In this example, the callback procedure receives and


displays a non-empty window name. When you click "Yes" it
leaves the window in the system, and when you click "No" it
closes the window by sending it a "WM_CLOSE" message.
Each callback procedure upon exit must return a non-zero
value in the eax register, otherwise the list of objects will stop.
It is necessary to refine this program so that it searches for and
closes windows only with the given name. To do this, you need
to use the function of comparing text strings:
call lstrcmp, offset WND_NAME, offset Text_to_close

Each student must choose his own window.

The following example shows a list of registry keys by


index. The most secure HKEY_CURRENT_USER partition
with the specified key is selected as the global registry
partition, for example: "Software\Microsoft\Internet Explorer":

.586
.model flat,STDCALL
extrn ExitProcess:Proc, RegOpenKeyA: Proc, RegEnumKeyExA:Proc
extrn MessageBoxA:Proc
HKEY_CURRENT_USER equ 80000001h
.data
SizeKeyClassName dd 260 ; maximal size of key name
KeyClassName db 'Software\Microsoft\Internet
Explorer',260 dup(0)
SizeSubKeyName dd 260
SubKeyName db 260 dup(0)
IndexKey dd 0 ; Key index (input value)
KeyHandle dd 0 ; Key handle;
KeyTime dq 0 ; creation or changed packed time
;===========================================
.code
Start: push offset KeyHandle ; The result address
push offset KeyClassName ; KeyName;
push HKEY_CURRENT_USER ; Section of the registry;
call RegOpenKeyA ; System API call;
or eax,eax
jnz STOP ; On error go to Stop.
NEXT_KEY:
; Refresh size of buffer
mov SizeSubKeyName,260
mov SizeKeyClassName,260
push offset KeyTime ; result time
push offset SizeKeyClassName ; result size
push offset KeyClassName ; result name
push 0 ; not used
push offset SizeSubKeyName ; result size
push offset SubKeyName ; result name
push IndexKey ; input index
push KeyHandle ; input handle.
call RegEnumKeyExA ; Get all key information
cmp eax,0 ; якщо eax=0, то успішне виконання,
jnz STOP ; інакше підключів не існує

call MessageBoxA,0,offset SubKeyName,offset KeyClassName,1


inc IndexKey ; next index
cmp eax,1 ; if “OK”,
jz NEXT_KEY ; go to next key.
STOP: call ExitProcess,0
;------------------------------------------------------------
End Start

You need to first find out the time of creation of each key
that is displayed by this program, and then create your own key
in the "Software" section, display the time of its creation (the
same time is the time of change), and then delete the created
key. To get the key generation time, replace the loop
termination command "jz NEXT_KEY" with "jz
GET_KEY_TIME". Place the new label GET_KEY_TIME
after the call ExitProcess,0 on a separate line. Start a new
program fragment with the time format conversion function:

call FileTimeToSystemTime, offset KeyTime, offset SYSTEMTIME

then add the time output snippet from the lab that outputted the
system time without the "GetLocalTime" operation. End the
fragment with a "jmp NEXT_KEY" transition to continue the
key listing loop.
To create your own key, use the following program:

.586
.model flat,stdcall
extrn RegCreateKeyExA:Proc, RegSetValueExA:Proc,
RegCloseKey:Proc, MessageBoxA:Proc, ExitProcess:Proc, lstrlen:Proc
HKEY_CURRENT_USER equ 80000001h
KEY_ALL_ACCESS equ 0f003fh
REG_SZ equ 1 ; тип даних ключа – текстовий рядок
.data
KEY_NAME db "SOFTWARE\Lab_work\Registration",0
NAME1 db "Студент",0
VALUE1 db "Петренко Петро Петрович",0
ERR_TEXT1 db "Помилка створення ключа",0
DISP_TEXT1 db "Створили новий ключ",0
DISP_TEXT2 db "Відкрили існучий ключ",0
Result_KEY dd 0
Disposition dd 0
.code
Start: call RegCreateKeyExA,HKEY_CURRENT_USER,offset
KEY_NAME,0,0,0,KEY_ALL_ACCESS,0,offset Result_KEY,offset
Disposition
cmp eax,0
jz C_OK1
call MessageBoxA,0,offset ERR_TEXT1,0,10h
C_OK1:
.if Disposition==1
call MessageBoxA,0,offset KEY_NAME,offset DISP_TEXT1,40h
.endif
.if Disposition==2
call MessageBoxA,0,offset KEY_NAME,offset DISP_TEXT2,30h
.endif
call lstrlen,offset VALUE1
call RegSetValueExA, Result_KEY, offset NAME1,0,REG_SZ,
offset VALUE1,eax
call RegCloseKey, Result_KEY
call ExitProcess,0
end Start

Run the system key viewer REGEDIT.EXE to verify that


the key was not present before running this program.
After running your program, the key should appear. You
can delete the key using the REGEDIT.EXE system program,
or using the following program:

.586
.model flat, stdcall
Extrn RegDeleteKeyA:Proc, MessageBoxA:Proc, ExitProcess:Proc
HKEY_CURRENT_USER equ 80000001h
.data
TEXT_DELETE_KEY db "Key has been deleted:",0
TEXT_ERR_KEY db "Check the next registry key:",0
KEY_NAME1 db "SOFTWARE\Lab_work\Registration",0
KEY_NAME2 db "SOFTWARE\Lab_work",0
.code
Start: call RegDeleteKeyA, HKEY_CURRENT_USER, offset
KEY_NAME1
call RegDeleteKeyA, HKEY_CURRENT_USER, offset
KEY_NAME2
.if eax==0
call MessageBoxA, 0, offset KEY_NAME1, offset
TEXT_DELETE_KEY, 40h
jmp STOP
.endif
call MessageBoxA, 0, offset KEY_NAME1, offset
TEXT_ERR_KEY, 10h
STOP: call ExitProcess,0
end Start

Make a program to get the generation time of your key. If


there is no key, the program should report this.

WORK PERFORMANCE PROCEDURE

1. Check the functionality and explain the operation of all


submitted programs as described in the theoretical part.
2. Rework the program of specialized folders in such a way
that, in addition to the name of the folder, it outputs the
value of the index.
3. Modify the folder selection program so that it copies the
given file from the desktop to the selected folder.
4. Write a program to install a desktop image from a file
located in the "My Pictures" folder. To do this, get the
name of the specialized directory, attach the "\" character to
it using the lstrcat function, and the name of the BMP file.
Use the SystemParametersInfoA function (see help) to set a
new desktop image.
5. Create a program that would close all windows that have a
specified 4-character fragment in their name.
6. Among the given registry keys, find only those keys that
were modified after the given date. To do this, use the
SystemTimeToFileTime function and compare the times
according to the rule of comparing 8-byte numbers.
7. Prove that this registry key belongs to you.

CONTROL QUESTIONS
1. How do the functions of the list of system objects work?
2. What is a specialized system folder?
3. How does the registry differ from a specialized folder?
4. What specialized folders do you know?
5. What is a folder handle?
6. How to get the name of the specialized folder through the
handle?
7. What does the SystemParametersInfoA function do?
8. What list API functions do you know?
9. How to get the name of the window class?
10. What sections exist in the system registry?

WORK REPORT FORM


The report is a document that the student
has successfully completed the work.

1. The goal set before the work in one's own words;


2. Brief content of theoretical information in your own words;
3. Texts of all debugged programs with their comments;
4. Answers to control questions in your own words;
5. Conclusions on the specifics of the application of the acquired knowledge
or comments on the performance of the work and methodical support.

You might also like