SlideShare a Scribd company logo
maXbox Starter 37
Start API Coding V2
1.1 A Programming Interface
Today we step through the API Coding of Windows.
Although, you probably wondered how they get those nice and fancy
graphical user interfaces (GUI) in windows programs that don't have just a
black screen. Well, these GUI1
programs are called Win32 API programs.
Learn how to make API calls with a black screen and other GUI objects in
Win 32 programming.
Lets start with our first function of a API call:
if FConnect then
Result:= WNetConnectionDialog(GetForegroundWindow,
RESOURCETYPE_DISK) = NO_ERROR
The WNetConnectionDialog function starts a general browsing dialog box
for connecting to network resources. The function requires a handle to the
owner window for the visual dialog box.
Syntax in C++
DWORD WNetConnectionDialog(
_In_ HWND hwnd,
_In_ DWORD dwType);
You do have 2 parameters: A handle to the owner window for the dialog
box and dwType as a resource type to allow connections to.
Also the return value as DWORD has to be considered:
If the function succeeds, the return value is NO_ERROR. If the user cancels
the dialog box, the function returns –1 as the boolean result above.
1
Non Graphical are called CLI (Command Line Interface ) or just Console
If the function fails, the return value is a defined system error code, such
as one of the following values:
ERROR_EXTENDED_ERROR
A network-specific error occurred. To obtain a description of the error, call
the WNetGetLastError function.
ERROR_INVALID_PASSWORD
The specified password is invalid.
ERROR_NO_NETWORK
The network is unavailable.
ERROR_NOT_ENOUGH_MEMORY
There is insufficient memory to start the dialog box.
If the user clicks OK in the dialog box, the requested network connection
will have been made when the WNetConnectionDialog function returns.
What about a password to connect in the dialogue of the API call?
2
If the function attempts to make a connection and the network provider
returns the message ERROR_INVALID_PASSWORD, the system prompts the
user to enter a password. The system uses the new password in another
attempt to make the net share connection.
But where does this function come from?
They use the windows 32-bit application programming interface, which
basically means interacting with Win operating systems and libraries such
as Win XP or 7 or 8 and the concerning DLL.
So the same call is valuable from a DLL:
function MyNETConnect(hw: hwnd; dw: dword): Longint;
external 'WNetConnectionDialog@Mpr.dll stdcall';
In this tutorial, you will learn how to use an external function with the
Win32 API to make wonderful and wise applications. You see the library is
called Mpr.dll as the external DLL.
And this is how we call the external function:
if MyNETConnect(GetForegroundWindow, RESOURCETYPE_DISK)
= NO_ERROR then writeln('connect dialog success');
You do not always need to know the following datatypes in order to use
Win32 API, the lesson here is, that most Win32 types are similar, if not the
same as C++ or Object Pascal datatypes. You are free to use standard C+
+ or Pascal datatypes to express any Win32 types.
A lot of the types in Win32 API, are synonyms and are not really that
important to know or to learn cause you can search for type mapping.
 It is important to declare your globals and definitions at the top of your
program. You can also wrap an API function like this:
function TJvNetworkConnect_Execute: Boolean;
var fconnect: boolean;
begin
//RESOURCETYPE_DISK
//WNetDisconnectDialog
fconnect:= true;
if fconnect then
Result:= WnetConnectionDialog(GetForegroundWindow,
RESOURCETYPE_DISK) = NO_ERROR
else
Result:= WnetDisconnectDialog(GetForegroundWindow,
RESOURCETYPE_DISK) = NO_ERROR;
end;
3
HWNDs (window handles) are usually used for GUI elements; they
represent the actual window or window elements of a program. UINT is an
unsigned integer and WPARAM and LPARAM are parameter messages that
windows uses to add more data into a message.
In our example it is the first parameter: GetForegroundWindow.
But be carefully it is also a function itself to get or pass the HWND!
GetForegroundWindow() retrieves a handle to the foreground window
(the window with which the user is currently working). The system assigns
a slightly higher priority to the thread that creates the foreground window
than it does to other threads.
HWND WINAPI GetForegroundWindow(void);
The return value is a handle to the foreground window. The foreground
window can be NULL in certain circumstances, such as when a window is
losing activation. So we use in fact 2 API functions:
WnetConnectionDialog(GetForegroundWindow,
RESOURCETYPE_DISK) = NO_ERROR
WnetConnectionDialog(GetForegroundWindow,
RESOURCETYPE_DISK) = NO_ERROR
Lib: Mpr.dll → WnetConnectionDialog
Lib: User32.dll → GetForegroundWindow
Then in the end the system uses the new password in another attempt to
make a connection.
The WNetCancelConnection2 function or WnetDisconnectDialog cancels
an existing network connection. You can also call the function to remove
remembered network connections that are not currently connected.
4
The cancel function closes a handle and the object associated with that
handle. After being closed, the handle is of course no longer valid. This
closes handles associated with access tokens, communications devices,
console inputs, console screen buffers, events, files, file mappings, jobs,
mail-slots, mutexes, named pipes, processes, semaphores, sockets, and
threads.
This is so important cause resources or handles evolves in hundreds of
numbers:
So a next call to an API function is the Object-oriented call:
// OO API Call:
with TJvConnectNetwork.Create(self) do begin
Execute;
Free;
end;
The method Execute waits till the user responds and then the object is
freed to save memory and consistency. Such interactions of users are
mostly logged in an application log.
The application log (see picture) contains those API or other events logged
by applications or programs. For example, a database program might
record a file error in the application log or the new connected share. You
as a developer decide which events to log.
To log a sound in a multimedia app for e.g. you have to set a song first:
playMP3(mp3path);
closeMP3;
DebugOutputString('closeMP3: '+ mp3path);
5
In a shortlink %windir%system32eventvwr.msc /s you start a log:
 Analytic or test events are published in high volume. They describe
program operation and indicate problems that can't be handled by user
tasks or intervention.
Finally, if a high-resolution performance counter exists on the system, you
can use the QueryPerformanceFrequency Win API function to express the
frequency, in counts per second. The value of the count is processor
dependent!
QueryPerformanceFrequency returns the number of "ticks" per seconds -
it is the amount that the counter, QueryPerformanceCounter, will
increment in a second.
In maXbox you can also map (connect) or disconnect a network drive
without a dialog as console or shell call!:
ConnectDrive('Z:', 'ServernameC', True, True);
Const SHARENAME = 'MAXBOX8UsersPublic';
if ConnectDrive('Z:','MAXBOX8UsersPublic', True,True) = NO_ERROR then
writeln('Net Share Z: Connected'); //see appendix with const
DisconnectNetDrive('Z:', True, True, True);
6
Test the script with F9 / F2 or press Compile. So far now we’ll open the
API-function example: 580_indystacksearch_geo2_winapi_tut37.txt
This is the huge test driven script, a better and smaller demo script to
start is the following:
617_API_coding_tut37.txt
http://www.softwareschule.ch/examples/617_API_coding_tut37.txt
Hope you did already work with the Starter 28 on DLL Code topics:
http://www.softwareschule.ch/download/maxbox_starter28.pdf
http://www.softwareschule.ch/download/maxbox_starter37.pdf
Conclusion Stepping through code is one of the most basic
debugging operations, yet it still needs to be mentioned here. Several
principles are commonly used to govern the process of designing APIs.
They proposed the concept of information hiding in 1972. The principle of
information hiding is that one may divide software into modules, each of
which has a specified interface.
The interfaces hide the implementation details of the modules so that
users of modules need not understand the complexities inside the
modules.
These interfaces are APIs, and as a result, APIs should be designed in order
to expose only those details of modules that are necessary for clients to
know in order to use the modules effectively.
Win programs register themselves on the operating system OS and work
with one loop for messages. In addition, the message loop goes through a
process function that handles all the windows messages and delivers what
the user or operating system demands.
“If the brain were so simple we could understand it, we would be so simple
we couldn't.” Lyall Watson
Feedback @ max@kleiner.com
Literature: Kleiner et al., Patterns konkret, 2003, Software & Support
http://www.softwareschule.ch/download/codesign_2015.pdf
http://www.rosseeld.be/DRO/Delphi/Delphi%20WinAPI.htm
https://github.com/maxkleiner/maXbox3/releases
7
1.2 Appendix Main Code and Event Log Study with Assert
// DLL Declaration of LIB Mpr.dll to call it direct:
// TODO: Copy a file in a connected share path
Function MyNETConnect(hw: hwnd; dw: dword): Longint;
External 'WNetConnectionDialog@Mpr.dll stdcall';
Const SHARENAME = 'MAXBOX8UsersPublic';
// OO Call:
with TJvConnectNetwork.Create(self) do begin
Execute;
free;
end;
// API Call function:
TJvNetworkConnect_Execute;
// DLL Call: MyNETConnect(GetForegroundWindow, RESOURCETYPE_DISK)
if MyNETConnect(GetForegroundWindow, RESOURCETYPE_DISK) =
NO_ERROR then
writeln('connect dialog of DLL call');
// without Dialog:
if ConnectDrive('Z:',SHARENAME, True,True) = NO_ERROR then
writeln('Net Share '+SHARENAME+' on Z: Connected');
if DisconnectNetDrive('Z:', True, True, True) = NO_ERROR then
writeln('Net Share '+SHARENAME+' on Z: Disconnected!');
PROCEDURE Assert(Cond: boolean; const Msg: string);
var
progSeg,
progOfs: word;
begin
asm
mov ax, [bp+04]
mov es, ax
mov ax, word ptr es:0
mov progSeg, ax
mov ax, [bp+02]
mov progOfs, ax
end;
8
if (Cond = FALSE) then begin
mmDebug.Lines.Add(Msg + ' at location ' +
IntToHex(progSeg, 4) +':' +IntToHex(progOfs, 4) );
ShowModal;
end;
end;
// WriteToOSEventLog//
procedure WriteToOSEventLog(const logName, logCaption, logDetails : UnicodeString;
const logRawData : String = '');
var
eventSource : THandle;
detailsPtr : array [0..1] of PWideChar;
begin
if logName<>'' then
eventSource:=RegisterEventSourceW(nil, PWideChar(logName))
else eventSource:=RegisterEventSourceW(nil,
PWideChar(ChangeFileExt(ExtractFileName(ParamStr(0)), '')));
if eventSource>0 then begin
try
detailsPtr[0]:=PWideChar(logCaption);
detailsPtr[1]:=PWideChar(logDetails);
ReportEventW(eventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, nil,
2, Length(logRawData),
@detailsPtr, Pointer(logRawData));
finally
DeregisterEventSource(eventSource);
end;
end;
end;
Check the script! Script Example: maxbox3examples318_excel_export3
9

More Related Content

What's hot

Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computersimran153
 
visual basic for the beginner
visual basic for the beginnervisual basic for the beginner
visual basic for the beginnerSalim M
 
Shape12 6
Shape12 6Shape12 6
Shape12 6pslulli
 

What's hot (8)

Visual basic ppt for tutorials computer
Visual basic ppt for tutorials computerVisual basic ppt for tutorials computer
Visual basic ppt for tutorials computer
 
visual basic for the beginner
visual basic for the beginnervisual basic for the beginner
visual basic for the beginner
 
visual basic programming
visual basic programmingvisual basic programming
visual basic programming
 
Shape12 6
Shape12 6Shape12 6
Shape12 6
 
Chapter03 Ppt
Chapter03 PptChapter03 Ppt
Chapter03 Ppt
 
Hacking ingress
Hacking ingressHacking ingress
Hacking ingress
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Visusual basic
Visusual basicVisusual basic
Visusual basic
 

Viewers also liked

maXbox Blix the Programmer
maXbox Blix the ProgrammermaXbox Blix the Programmer
maXbox Blix the ProgrammerMax Kleiner
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphiMax Kleiner
 
Arduino training program
Arduino training programArduino training program
Arduino training programMax Kleiner
 
Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3Max Kleiner
 
Arduino Teaching Program
Arduino Teaching ProgramArduino Teaching Program
Arduino Teaching ProgramMax Kleiner
 

Viewers also liked (6)

Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
maXbox Blix the Programmer
maXbox Blix the ProgrammermaXbox Blix the Programmer
maXbox Blix the Programmer
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphi
 
Arduino training program
Arduino training programArduino training program
Arduino training program
 
Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3Arduino LED maXbox starter18_3
Arduino LED maXbox starter18_3
 
Arduino Teaching Program
Arduino Teaching ProgramArduino Teaching Program
Arduino Teaching Program
 

Similar to Tutorial 37 API Coding

Selje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfSelje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfEric Selje
 
Android best training-in-mumbai
Android best training-in-mumbaiAndroid best training-in-mumbai
Android best training-in-mumbaivibrantuser
 
DLL Tutor maXbox starter28
DLL Tutor maXbox starter28DLL Tutor maXbox starter28
DLL Tutor maXbox starter28Max Kleiner
 
introduction to_mfc
 introduction to_mfc introduction to_mfc
introduction to_mfctuttukuttu
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialAbid Khan
 
Production Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyProduction Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyBrian Lyttle
 
Diploma ii cfpc u-1 introduction to c language
Diploma ii  cfpc u-1 introduction to c languageDiploma ii  cfpc u-1 introduction to c language
Diploma ii cfpc u-1 introduction to c languageRai University
 
Mca i pic u-1 introduction to c language
Mca i pic u-1 introduction to c languageMca i pic u-1 introduction to c language
Mca i pic u-1 introduction to c languageRai University
 
introduction to c language
 introduction to c language introduction to c language
introduction to c languageRai University
 
Btech i pic u-1 introduction to c language
Btech i pic u-1 introduction to c languageBtech i pic u-1 introduction to c language
Btech i pic u-1 introduction to c languageRai University
 
Btec Business Level 3 Unit 14 M1
Btec Business Level 3 Unit 14 M1Btec Business Level 3 Unit 14 M1
Btec Business Level 3 Unit 14 M1Rachel Phillips
 
Debugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsDebugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsPVS-Studio
 
Bsc cs i pic u-1 introduction to c language
Bsc cs i pic u-1 introduction to c languageBsc cs i pic u-1 introduction to c language
Bsc cs i pic u-1 introduction to c languageRai University
 
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...Codemotion
 
Electrical shop management system project report.pdf
Electrical shop management system project report.pdfElectrical shop management system project report.pdf
Electrical shop management system project report.pdfKamal Acharya
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32Eden Shochat
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 

Similar to Tutorial 37 API Coding (20)

VB.Net GUI Unit_01
VB.Net GUI Unit_01VB.Net GUI Unit_01
VB.Net GUI Unit_01
 
Oopp Lab Work
Oopp Lab WorkOopp Lab Work
Oopp Lab Work
 
Selje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfSelje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdf
 
Android best training-in-mumbai
Android best training-in-mumbaiAndroid best training-in-mumbai
Android best training-in-mumbai
 
DLL Tutor maXbox starter28
DLL Tutor maXbox starter28DLL Tutor maXbox starter28
DLL Tutor maXbox starter28
 
Mantra
MantraMantra
Mantra
 
introduction to_mfc
 introduction to_mfc introduction to_mfc
introduction to_mfc
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Production Debugging at Code Camp Philly
Production Debugging at Code Camp PhillyProduction Debugging at Code Camp Philly
Production Debugging at Code Camp Philly
 
Diploma ii cfpc u-1 introduction to c language
Diploma ii  cfpc u-1 introduction to c languageDiploma ii  cfpc u-1 introduction to c language
Diploma ii cfpc u-1 introduction to c language
 
Mca i pic u-1 introduction to c language
Mca i pic u-1 introduction to c languageMca i pic u-1 introduction to c language
Mca i pic u-1 introduction to c language
 
introduction to c language
 introduction to c language introduction to c language
introduction to c language
 
Btech i pic u-1 introduction to c language
Btech i pic u-1 introduction to c languageBtech i pic u-1 introduction to c language
Btech i pic u-1 introduction to c language
 
Btec Business Level 3 Unit 14 M1
Btec Business Level 3 Unit 14 M1Btec Business Level 3 Unit 14 M1
Btec Business Level 3 Unit 14 M1
 
Debugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programsDebugging and optimization of multi-thread OpenMP-programs
Debugging and optimization of multi-thread OpenMP-programs
 
Bsc cs i pic u-1 introduction to c language
Bsc cs i pic u-1 introduction to c languageBsc cs i pic u-1 introduction to c language
Bsc cs i pic u-1 introduction to c language
 
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
 
Electrical shop management system project report.pdf
Electrical shop management system project report.pdfElectrical shop management system project report.pdf
Electrical shop management system project report.pdf
 
Android 101 Session @thejunction32
Android 101 Session @thejunction32Android 101 Session @thejunction32
Android 101 Session @thejunction32
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 

More from Max Kleiner

EKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfEKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfMax Kleiner
 
EKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfEKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfMax Kleiner
 
maXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementmaXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementMax Kleiner
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4Max Kleiner
 
maXbox Starter87
maXbox Starter87maXbox Starter87
maXbox Starter87Max Kleiner
 
maXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapmaXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapMax Kleiner
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detectionMax Kleiner
 
BASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationBASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationMax Kleiner
 
EKON 24 ML_community_edition
EKON 24 ML_community_editionEKON 24 ML_community_edition
EKON 24 ML_community_editionMax Kleiner
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingMax Kleiner
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP Max Kleiner
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures CodingMax Kleiner
 
NoGUI maXbox Starter70
NoGUI maXbox Starter70NoGUI maXbox Starter70
NoGUI maXbox Starter70Max Kleiner
 
maXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIIMax Kleiner
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VIMax Kleiner
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning VMax Kleiner
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3Max Kleiner
 
EKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsEKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsMax Kleiner
 

More from Max Kleiner (20)

EKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfEKON26_VCL4Python.pdf
EKON26_VCL4Python.pdf
 
EKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfEKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdf
 
maXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementmaXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_Implement
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
maXbox Starter87
maXbox Starter87maXbox Starter87
maXbox Starter87
 
maXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapmaXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmap
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detection
 
BASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationBASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data Visualisation
 
EKON 24 ML_community_edition
EKON 24 ML_community_editionEKON 24 ML_community_edition
EKON 24 ML_community_edition
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures Coding
 
NoGUI maXbox Starter70
NoGUI maXbox Starter70NoGUI maXbox Starter70
NoGUI maXbox Starter70
 
maXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VII
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning V
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
EKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsEKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_Diagrams
 

Recently uploaded

一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单ukgaet
 
Webinar One View, Multiple Systems No-Code Integration of Salesforce and ERPs
Webinar One View, Multiple Systems No-Code Integration of Salesforce and ERPsWebinar One View, Multiple Systems No-Code Integration of Salesforce and ERPs
Webinar One View, Multiple Systems No-Code Integration of Salesforce and ERPsCEPTES Software Inc
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单ewymefz
 
Business update Q1 2024 Lar España Real Estate SOCIMI
Business update Q1 2024 Lar España Real Estate SOCIMIBusiness update Q1 2024 Lar España Real Estate SOCIMI
Business update Q1 2024 Lar España Real Estate SOCIMIAlejandraGmez176757
 
Computer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage sComputer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage sMAQIB18
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单enxupq
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单ewymefz
 
How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?DOT TECH
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单yhkoc
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单vcaxypu
 
Jpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJames Polillo
 
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单vcaxypu
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundOppotus
 
tapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatheahmadsaood
 
Tabula.io Cheatsheet: automate your data workflows
Tabula.io Cheatsheet: automate your data workflowsTabula.io Cheatsheet: automate your data workflows
Tabula.io Cheatsheet: automate your data workflowsalex933524
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单ewymefz
 
Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...
Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...
Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...Domenico Conte
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单nscud
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .NABLAS株式会社
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay
 

Recently uploaded (20)

一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
一比一原版(UVic毕业证)维多利亚大学毕业证成绩单
 
Webinar One View, Multiple Systems No-Code Integration of Salesforce and ERPs
Webinar One View, Multiple Systems No-Code Integration of Salesforce and ERPsWebinar One View, Multiple Systems No-Code Integration of Salesforce and ERPs
Webinar One View, Multiple Systems No-Code Integration of Salesforce and ERPs
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单
 
Business update Q1 2024 Lar España Real Estate SOCIMI
Business update Q1 2024 Lar España Real Estate SOCIMIBusiness update Q1 2024 Lar España Real Estate SOCIMI
Business update Q1 2024 Lar España Real Estate SOCIMI
 
Computer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage sComputer Presentation.pptx ecommerce advantage s
Computer Presentation.pptx ecommerce advantage s
 
一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单一比一原版(QU毕业证)皇后大学毕业证成绩单
一比一原版(QU毕业证)皇后大学毕业证成绩单
 
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
一比一原版(UPenn毕业证)宾夕法尼亚大学毕业证成绩单
 
How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?How can I successfully sell my pi coins in Philippines?
How can I successfully sell my pi coins in Philippines?
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
一比一原版(ArtEZ毕业证)ArtEZ艺术学院毕业证成绩单
 
Jpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization SampleJpolillo Amazon PPC - Bid Optimization Sample
Jpolillo Amazon PPC - Bid Optimization Sample
 
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
一比一原版(RUG毕业证)格罗宁根大学毕业证成绩单
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
 
tapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive datatapal brand analysis PPT slide for comptetive data
tapal brand analysis PPT slide for comptetive data
 
Tabula.io Cheatsheet: automate your data workflows
Tabula.io Cheatsheet: automate your data workflowsTabula.io Cheatsheet: automate your data workflows
Tabula.io Cheatsheet: automate your data workflows
 
一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单一比一原版(BU毕业证)波士顿大学毕业证成绩单
一比一原版(BU毕业证)波士顿大学毕业证成绩单
 
Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...
Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...
Professional Data Engineer Certification Exam Guide  _  Learn  _  Google Clou...
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .社内勉強会資料_LLM Agents                              .
社内勉強会資料_LLM Agents                              .
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
 

Tutorial 37 API Coding

  • 1. maXbox Starter 37 Start API Coding V2 1.1 A Programming Interface Today we step through the API Coding of Windows. Although, you probably wondered how they get those nice and fancy graphical user interfaces (GUI) in windows programs that don't have just a black screen. Well, these GUI1 programs are called Win32 API programs. Learn how to make API calls with a black screen and other GUI objects in Win 32 programming. Lets start with our first function of a API call: if FConnect then Result:= WNetConnectionDialog(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR The WNetConnectionDialog function starts a general browsing dialog box for connecting to network resources. The function requires a handle to the owner window for the visual dialog box. Syntax in C++ DWORD WNetConnectionDialog( _In_ HWND hwnd, _In_ DWORD dwType); You do have 2 parameters: A handle to the owner window for the dialog box and dwType as a resource type to allow connections to. Also the return value as DWORD has to be considered: If the function succeeds, the return value is NO_ERROR. If the user cancels the dialog box, the function returns –1 as the boolean result above. 1 Non Graphical are called CLI (Command Line Interface ) or just Console
  • 2. If the function fails, the return value is a defined system error code, such as one of the following values: ERROR_EXTENDED_ERROR A network-specific error occurred. To obtain a description of the error, call the WNetGetLastError function. ERROR_INVALID_PASSWORD The specified password is invalid. ERROR_NO_NETWORK The network is unavailable. ERROR_NOT_ENOUGH_MEMORY There is insufficient memory to start the dialog box. If the user clicks OK in the dialog box, the requested network connection will have been made when the WNetConnectionDialog function returns. What about a password to connect in the dialogue of the API call? 2
  • 3. If the function attempts to make a connection and the network provider returns the message ERROR_INVALID_PASSWORD, the system prompts the user to enter a password. The system uses the new password in another attempt to make the net share connection. But where does this function come from? They use the windows 32-bit application programming interface, which basically means interacting with Win operating systems and libraries such as Win XP or 7 or 8 and the concerning DLL. So the same call is valuable from a DLL: function MyNETConnect(hw: hwnd; dw: dword): Longint; external 'WNetConnectionDialog@Mpr.dll stdcall'; In this tutorial, you will learn how to use an external function with the Win32 API to make wonderful and wise applications. You see the library is called Mpr.dll as the external DLL. And this is how we call the external function: if MyNETConnect(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR then writeln('connect dialog success'); You do not always need to know the following datatypes in order to use Win32 API, the lesson here is, that most Win32 types are similar, if not the same as C++ or Object Pascal datatypes. You are free to use standard C+ + or Pascal datatypes to express any Win32 types. A lot of the types in Win32 API, are synonyms and are not really that important to know or to learn cause you can search for type mapping.  It is important to declare your globals and definitions at the top of your program. You can also wrap an API function like this: function TJvNetworkConnect_Execute: Boolean; var fconnect: boolean; begin //RESOURCETYPE_DISK //WNetDisconnectDialog fconnect:= true; if fconnect then Result:= WnetConnectionDialog(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR else Result:= WnetDisconnectDialog(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR; end; 3
  • 4. HWNDs (window handles) are usually used for GUI elements; they represent the actual window or window elements of a program. UINT is an unsigned integer and WPARAM and LPARAM are parameter messages that windows uses to add more data into a message. In our example it is the first parameter: GetForegroundWindow. But be carefully it is also a function itself to get or pass the HWND! GetForegroundWindow() retrieves a handle to the foreground window (the window with which the user is currently working). The system assigns a slightly higher priority to the thread that creates the foreground window than it does to other threads. HWND WINAPI GetForegroundWindow(void); The return value is a handle to the foreground window. The foreground window can be NULL in certain circumstances, such as when a window is losing activation. So we use in fact 2 API functions: WnetConnectionDialog(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR WnetConnectionDialog(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR Lib: Mpr.dll → WnetConnectionDialog Lib: User32.dll → GetForegroundWindow Then in the end the system uses the new password in another attempt to make a connection. The WNetCancelConnection2 function or WnetDisconnectDialog cancels an existing network connection. You can also call the function to remove remembered network connections that are not currently connected. 4
  • 5. The cancel function closes a handle and the object associated with that handle. After being closed, the handle is of course no longer valid. This closes handles associated with access tokens, communications devices, console inputs, console screen buffers, events, files, file mappings, jobs, mail-slots, mutexes, named pipes, processes, semaphores, sockets, and threads. This is so important cause resources or handles evolves in hundreds of numbers: So a next call to an API function is the Object-oriented call: // OO API Call: with TJvConnectNetwork.Create(self) do begin Execute; Free; end; The method Execute waits till the user responds and then the object is freed to save memory and consistency. Such interactions of users are mostly logged in an application log. The application log (see picture) contains those API or other events logged by applications or programs. For example, a database program might record a file error in the application log or the new connected share. You as a developer decide which events to log. To log a sound in a multimedia app for e.g. you have to set a song first: playMP3(mp3path); closeMP3; DebugOutputString('closeMP3: '+ mp3path); 5
  • 6. In a shortlink %windir%system32eventvwr.msc /s you start a log:  Analytic or test events are published in high volume. They describe program operation and indicate problems that can't be handled by user tasks or intervention. Finally, if a high-resolution performance counter exists on the system, you can use the QueryPerformanceFrequency Win API function to express the frequency, in counts per second. The value of the count is processor dependent! QueryPerformanceFrequency returns the number of "ticks" per seconds - it is the amount that the counter, QueryPerformanceCounter, will increment in a second. In maXbox you can also map (connect) or disconnect a network drive without a dialog as console or shell call!: ConnectDrive('Z:', 'ServernameC', True, True); Const SHARENAME = 'MAXBOX8UsersPublic'; if ConnectDrive('Z:','MAXBOX8UsersPublic', True,True) = NO_ERROR then writeln('Net Share Z: Connected'); //see appendix with const DisconnectNetDrive('Z:', True, True, True); 6
  • 7. Test the script with F9 / F2 or press Compile. So far now we’ll open the API-function example: 580_indystacksearch_geo2_winapi_tut37.txt This is the huge test driven script, a better and smaller demo script to start is the following: 617_API_coding_tut37.txt http://www.softwareschule.ch/examples/617_API_coding_tut37.txt Hope you did already work with the Starter 28 on DLL Code topics: http://www.softwareschule.ch/download/maxbox_starter28.pdf http://www.softwareschule.ch/download/maxbox_starter37.pdf Conclusion Stepping through code is one of the most basic debugging operations, yet it still needs to be mentioned here. Several principles are commonly used to govern the process of designing APIs. They proposed the concept of information hiding in 1972. The principle of information hiding is that one may divide software into modules, each of which has a specified interface. The interfaces hide the implementation details of the modules so that users of modules need not understand the complexities inside the modules. These interfaces are APIs, and as a result, APIs should be designed in order to expose only those details of modules that are necessary for clients to know in order to use the modules effectively. Win programs register themselves on the operating system OS and work with one loop for messages. In addition, the message loop goes through a process function that handles all the windows messages and delivers what the user or operating system demands. “If the brain were so simple we could understand it, we would be so simple we couldn't.” Lyall Watson Feedback @ max@kleiner.com Literature: Kleiner et al., Patterns konkret, 2003, Software & Support http://www.softwareschule.ch/download/codesign_2015.pdf http://www.rosseeld.be/DRO/Delphi/Delphi%20WinAPI.htm https://github.com/maxkleiner/maXbox3/releases 7
  • 8. 1.2 Appendix Main Code and Event Log Study with Assert // DLL Declaration of LIB Mpr.dll to call it direct: // TODO: Copy a file in a connected share path Function MyNETConnect(hw: hwnd; dw: dword): Longint; External 'WNetConnectionDialog@Mpr.dll stdcall'; Const SHARENAME = 'MAXBOX8UsersPublic'; // OO Call: with TJvConnectNetwork.Create(self) do begin Execute; free; end; // API Call function: TJvNetworkConnect_Execute; // DLL Call: MyNETConnect(GetForegroundWindow, RESOURCETYPE_DISK) if MyNETConnect(GetForegroundWindow, RESOURCETYPE_DISK) = NO_ERROR then writeln('connect dialog of DLL call'); // without Dialog: if ConnectDrive('Z:',SHARENAME, True,True) = NO_ERROR then writeln('Net Share '+SHARENAME+' on Z: Connected'); if DisconnectNetDrive('Z:', True, True, True) = NO_ERROR then writeln('Net Share '+SHARENAME+' on Z: Disconnected!'); PROCEDURE Assert(Cond: boolean; const Msg: string); var progSeg, progOfs: word; begin asm mov ax, [bp+04] mov es, ax mov ax, word ptr es:0 mov progSeg, ax mov ax, [bp+02] mov progOfs, ax end; 8
  • 9. if (Cond = FALSE) then begin mmDebug.Lines.Add(Msg + ' at location ' + IntToHex(progSeg, 4) +':' +IntToHex(progOfs, 4) ); ShowModal; end; end; // WriteToOSEventLog// procedure WriteToOSEventLog(const logName, logCaption, logDetails : UnicodeString; const logRawData : String = ''); var eventSource : THandle; detailsPtr : array [0..1] of PWideChar; begin if logName<>'' then eventSource:=RegisterEventSourceW(nil, PWideChar(logName)) else eventSource:=RegisterEventSourceW(nil, PWideChar(ChangeFileExt(ExtractFileName(ParamStr(0)), ''))); if eventSource>0 then begin try detailsPtr[0]:=PWideChar(logCaption); detailsPtr[1]:=PWideChar(logDetails); ReportEventW(eventSource, EVENTLOG_INFORMATION_TYPE, 0, 0, nil, 2, Length(logRawData), @detailsPtr, Pointer(logRawData)); finally DeregisterEventSource(eventSource); end; end; end; Check the script! Script Example: maxbox3examples318_excel_export3 9