Win32 API Calls From C#
With the simple example behind us,
let's review how to make calls to arbitrary Win32 APIs.
We can leverage the DllImport statement
to import and link any Win32 APIs into C#.
We’ll need to once again translate the C-style argument data types
to C# through the P/Invoke technique.
Let’s make a proof-of-concept example that imports MessageBoxA
and calls it from C#.
To simplify this, we’ll use the Visual Studio solution
we created for the Hello World example.
First we’ll look up MessageBox on pinvoke.net,
to help translate the C data types to C# data types.
To use MessageBoxA,
we need an import statement added inside the Program class,
but outside the Main method.
With the Win32 API imported,
we simply invoke it,
by supplying text and a caption.
However, Visual Studio highlights potential issues
with the DllImport statement due to missing namespaces.
To use the DllImport statement and invoke the Win32 APIs,
we have to use the two namespaces,
System.Diagnostics and System.Runtime.InteropServices.
In addition, we need the core System namespace
that provides us access to all basic data types.
At this point, we can compile the application without errors,
and launch it from the command prompt.
This should generate a popup with our text.
Now we’ve again demonstrated how to import and call Win32 APIs from C#
without having to use reflection,
in the next setion we’ll recreate our PowerShell shellcode runner in C#.