Accessing Windows API Constants and Structs for P/Invoke - c#

Quick question: How can I access the BN_CLICKED constant and other constants defined for the Win32 API from .NET? Are they defined in some library? Do I have to define them myself? If so, where can I find these values? And are the values version-specific between versions of Windows?

I find the PInvoke Interop Assistant to be really helpful:
http://blogs.microsoft.co.il/blogs/sasha/archive/2008/01/12/p-invoke-signature-generator.aspx.
It has almost everything and can convert the C++ to C#/VB for you. I rarely, if ever, resort to searching google/pinvoke.net anymore.
Here's the MSDN Magazine Article: http://msdn.microsoft.com/en-us/magazine/cc164193.aspx
The original January 2008 MSDN Magazine Article is now only available as a .CHM help file download, linked from the very bottom of https://msdn.microsoft.com/magazine/msdn-magazine-issues. (Column "CLR Inside Out: Marshaling between managed and unmanaged code.")
And here's the download: http://download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/CLRInsideOut2008_01.exe. The source code can be found at http://clrinterop.codeplex.com/.

You could download the Microsoft Platform SDK and take a look at the header files (*.h). E.g. the BN_CLICKED is defined in the winuser.h file.
Usually, if you just need one or two constants, a Google search and a look at the first few results is also sufficient, since the value is printed there.

http://pinvoke.net/ is an excellent resource for this many common P/Invoke definitions.

The MagNumDB website (by SO user Simon Mourier) is an easy way to look up constants:
http://www.magnumdb.com/search?q=BN_CLICKED

It's kind of a proof-of-concept, but I put together a script that can look up most any Windows API constant. Example usage:
PS > .\Get-WindowsSDKConstant.ps1 BN_CLICKED
0
PS > .\Get-WindowsSDKConstant.ps1 BN_DBLCLK
5
PS > .\Get-WindowsSDKConstant.ps1 WM_COMMAND
273
It requires you to download Visual Studio and the Windows 10 SDK, because behind-the-scenes it compiles a program that looks up the constant.
Finally, here's some answers to the asker's questions:
Are [the constants] defined in some library?
The authoritative source is the Windows Platform SDK
Do I have to define them myself?
They're not built-in to Windows or .NET, which means you'll probably define them yourself (or copy them from somewhere).
And are the values version-specific between versions of Windows?
They're very stable, because otherwise a program compiled for one version of Windows might stop working when a user upgrades to a newer version of Windows. Microsoft goes to great lengths to prevent this from happening.
However, I've seen at least one place where the constants are different depending on what platform/architecture you're compiling on. I wouldn't assume that just because your code works on x86 64-bit Windows, it'll work on ARM 32-bit Windows RT, for example.

Related

Creating .Net Wrappers for Windows API and COM DLLs

Let me start by saying that I don't know what I don't know at this point, so rather than specific answers, I'm also looking for better questions to ask, I think. My .Net/C# is solid enough, and my C/C++ is meh.
Lately, I'm finding that there are no libraries in the standard .Net framework to accomplish certain tasks, and while it's easy enough to download a third party library, I'd like to understand how to do it myself if one doesn't already exist.
In one recent case, I need to deal with MIDI in windows at a relatively low-level, and I accidentally found out that "winmm.dll" is the library I'll need to use by downloading a .net wrapper for MIDI and browsing through the source. I understand that I'll have to make a wrapper class and do the whole P/Invoke thing to make that happen.
The next thing I did was to search for documentation on the Windows API to figure out what was going on in the mystery box of "winmm.dll," and to my delight, there was a whole Windows SDK that I was able to download and read through. I went through the "getting started" section of "Windows Development" which covered some of the basics via C++. It talked a bit about COM, windows header files, and I know enough C++ to get the gist.
Now, I need help connecting the dots on a few issues:
1) The Windows SDK, so far, seems to suggest that I want to program to specific header files rather than the dlls themselves, but the .net wrappers I've found typically point to a specific .dll rather that a header file...
/// <summary>
/// Returns the number of MIDI input devices on this system.
/// </summary>
/// Win32 docs: http://msdn.microsoft.com/en-us/library/ms711608(VS.85).aspx
[DllImport("winmm.dll", SetLastError = true)]
public static extern UInt32 midiInGetNumDevs();
I was under the impression that a header file and DLL needed to be in the same folder, but the windows SDK includes a folder with all the windows header files, and no DLLs (I'm guessing the registry comes into play here for mapping to specific libraries?)? How do those header files eventually get mapped to actual libraries, and why does it seem like I don't even need to deal with header files to create a .Net wrapper?
2) I can't seem to find documentation on winmm.dll, but I have found references to the functions I'll likely need in the "Windows API" list in the Windows SDK, and I'm pretty sure that the code for those functions are in winmm.dll. How do I find the documentation for the specific libraries I'll need to begin creating my wrapper? If I didn't know that I was going to need winmm.dll to access windows MIDI functionality, how could I have figured that out myself?
3) Some DLLs are COM, some are plain windows DLLs, some are .net DLLs... how can I tell the different going forward? It seems that creating wrappers for the former two would require a different approach.
4) There is no page on MSDN for "Winmm.dll" listing all of its API, and I assume there's a good and practical reason for that, but I'm not sure what it is? I'm used to .Net land where I can figure out what a library does and how to use it almost without effort.
Thanks in advance for any insights.
The bible on this is Adam Nathans excellent book '.Net and COM the complete interoperability guide'
Includes PInvoke and several audio-type examples
1) The windows API documentation includes the header, library, and dll file for each method/enum/etc. I just didn't scroll down far enough when I read through to notice this. A header file doesn't necessarily have to be in the same directory as the dll; its contents are simply copy/pasted into the .c file when the program is compiled. The part I was missing here was the linking stage of compilation which I read about here
2) The documentation was there--I just had to look for it a little bit harder.
3) How can I detect the type of a dll? (COM, .NET, WIN32)
4) The api for audio could theoretically span multiple dlls, so the best course of action is to find the API documentation, find the methods you want to wrap, then figure out what dlls those methods are in, and then import each of those DLLs.

Where to find info about WM Windows Message codes?

I see here and there pro users answer lots of noobs like me questions with things like WM_PAINT = 0xf What should I search for to get complete list of this codes? are they all the same for all verions of windows? can they also used for other platforms?
Is this table of any help?
I'm not sure whether all Windows versions send all these message, but I'm pretty sure the codes aren't different between versions.
WM_PAINT = 0xf is a specific parameter for a certain method. those "codes" are usually needed with interlop stuff; using unmanaged core libraries such as user32 and kernel32.
You can find methods and their parameters like that on the site http://pinvoke.net.
For example, your example WM_PAINT is from User32.GetMessage
If you want a full list of specific WindowsMessage parameters; they can be found here.
You can find these in WinUser.h.
They cannot change between Windows versions (changing them would break binary compatibility with all Windows programs.
Sometimes we also need a message by its code, decimal or hexadecimal. I find the following table useful:
https://wiki.winehq.org/List_Of_Windows_Messages

Using Mapnik in .net environment

Has anybody used Mapnik for rendering Maps from .net c# environment? I would like to use it to render maps in a desktop application developed under .net4. I found it the best open source map renderer tool, much more better, than the well known sharpmap, dotspatial (...). The 'only' problem is that it was written in C++ and Python and does not have a trivial way to use it from C#.
Do you know any .net Mapnik wrappers? Do you know any sample code?
I've just published my attempts in C# bindings.
They are available at: http://sourceforge.net/projects/mapniknet/
Some good new about Mapnik-.Net integration:
"Another thing that will help Windows developers is a way to use Mapnik from .Net languages. Although a full .Net wrapper is too much work besides all the other issues, hopefully I can make a meaningful start and open the door for .Net developers to leverage Mapnik in their applications."
Source: Mapnik homepage http://mapnik.org/news/2011/jun/09/gsoc_2011_windows_build_system_introduction/
NET-Mapnik
You might want to give this a try. Its pretty recent and has a simple example with options to create vector tiles.
https://github.com/kernelsanders/NET-Mapnik
So, finally I hacked it. Not a nice solution, but it works at least. In nutshell it operates in the following way:
developed a python script, which takes parameters as command line arguments. (using python api of mapnik)
call this python script by shell fom c# code (Process)
after map image has been generated, I show it in SharpMap as a background layer
In case of any map refresh (zoom, pan) I regenerate 'mapnik map layer'. I have also some kind of cache, in which I can store generated maps, so I can make tricks by using earlier generated map images or pre-generate them (e.g. generate maps for the next zoom level when user uses zoom tool). I also use some asynchron calls to do this, so I can create 1-3 map images paralelly.
The weak part of this solution is the communication between python and c# modules. I could not find better than command line arguments + shell.
My solution works, mapnik is fast, can genarate my maps less than a sec.
If you have any advice on .net - python communication (NO ironpython, it is not suitable for manik api), pls write it here. Thx.
Do you know about TAO Project?
It is a .Net project that takes unmanaged opengle library to .Net Managed Form by calling DllIMport() in C#.
You must do it for Mapnik, simaliar to TAOFramework.net

How can I install a printer using .NET?

I have an .INF for a virtual printer that I need to install from a .NET Application. I have done this before using batch scripts, but I am looking for a snippet of code to do this in the .NET Framework.
There's nothing particular about the printer .INF, so any code that installs a printer from an INF in C# or VB.NET will work.
I believe this is possible via interop to native win32 APIs, but I've found its much, much easier just to use a System.Diagnostics.Process() to call into printui.dll via:
rundll32.exe printui.dll,PrintUIEntry /?
Perhaps you're already using that in the mentioned batch script, but if not the parameters are documented here: PrintUI.DLL User's Guide and Reference
Just be sure to test it against all operation systems you need to support. Some options either do not exist in all Windows releases or have been renamed (although I think they're the more esoteric options - installing an .INF will likely work across the board).
You are going to want to look at the WMI objects available. These give you a finer control of the local machine settings. Take a look at the WMI code creator from Microsoft, I believe this will generate some example code you can leverage to solve your problem.
Administering Printer Settings in C# for Flexible Printing
see this article, it uses an MS Platform SDK DLL called PRNADMIN to manage printers, printer-drivers, printer-ports, ...etc.
I personally use it in a commercial project to install a printer driver and change the printer port to local port to intercept the Postscript. and it works like a Charm.
Alternatively you can use some pre-installed vbscripts that come with windows in C:\Windows\system32\Printing_Admin_Scripts and here is a an articles for them:
http://technet.microsoft.com/en-us/library/cc771846.aspx
This is not the ideal solution, but if nobody else answers, you can create a temp batch file and invoke that through C#/VB.NET.
Someone else will probably know a more natural way to do this.
You will need to wrap the setup APIs using PINVOKE or a native COM object.

C# Console/CLI Interpreter?

I wonder if there is something like a standalone Version of Visual Studios "Immediate Window"? Sometimes I just want to test some simple stuff, like "DateTime.Parse("blah")" to see if that works. But everytime i have to create a new console application, put in my code and test it.
The Immediate Window sadly only works when I am debugging something. Could PowerShell do that? Just open a CLI similar to what cmd.exe does, allowing me to execute some C# code?
Linqpad - I use it like this all the time. http://www.linqpad.net/
Don't be misled by the name - that just describes the original motivation for it, not its functionality.
Just recently he released a version with proper statement completion - that's a chargeable add-on (the core tool is free), but a minute amount of money and well worth it, I think.
The Mono project includes an interactive C# shell, this may be just what you're looking for.
http://www.mono-project.com/CsharpRepl
C# Interactive window and csi.exe REPL were added to Visual Studio 2015 Update 1:
Introducing Interactive
The Interactive Window is back! The C# Interactive Window returns in Visual Studio 2015 Update 1 along with a couple other interactive treats:
C# Interactive. The C# Interactive window is essentially a read-eval-print-loop (REPL) that allows you to play and explore with .NET technologies while taking advantage of editor features like IntelliSense, syntax-coloring, etc. Learn more about how to use C# Interactive on Channel 9 or by reading our beginner’s walkthrough.
csi. If you don’t want to open Visual Studio to play around with C# or run a script file, you can access the interactive engine from the Developer Command Prompt. Type csi /path/myScript.csx to execute a script file or type simply csi to drop inside the command-line REPL.
Scripting APIs. The Scripting APIs give you the ability to execute snippets of C# code in a host-created execution environment. You can learn more about how to create your own C# script engine by checking out our code samples.
See What’s New in Visual Studio Update 1 for .NET Managed Languages.
Basically, now you have:
IDE REPL — C# Interactive window in VS
Script interpreter — csi foo.csx from Dev Cmd Prompt
Command line REPL — csi from Dev Cmd Prompt
Scripting API
Try scriptcs, it's not integrated into the VS IDE but it does let you type and run C# in a script window without the need for a project compiler etc...
Well, this isn't a direct answer to your question, but you could look at this tool:
Snippet Compiler
Also, if you want to see the IL produced, or similar, there is a tool that plugs into Reflector, called Snippy, based on the Snippy tool that Jon mentions in his own answer further down.
All of these are very nice to use.
As you suggest, PowerShell can do what you want. For example, to test your DateTime.Parse, the following one liner will do the trick:
PS C:\Documents and Settings\Dan> [System.DateTime]::Parse("Blah")
Exception calling "Parse" with "1" argument(s): "The string was not recognized as a valid DateTime. There is a unknown
word starting at index 0."
At line:1 char:25
+ [System.DateTime]::Parse( <<<< "Blah")
PS C:\Documents and Settings\Dan> [System.DateTime]::Parse("1/2/3")
01 February 2003 00:00:00
Note that the above uses the current release of PowerShell (v1.0). The next version of PowerShell will allows you to intermingle C# with PowerShell scripts more directly. To whet your appetite, watch this 7 minute screencast "C# to PowerShell" by Doug Finke. Very impressive!
If you're using Mono, there's this:
CsharpRepl
Don Box hacked something very simple up a few years ago too.
Along the lines of lassevk's answer, I've got "Snippy". This was developed for C# in Depth, and the UI is pretty rubbish, but it works - and lets you write extra members (methods, nested classes etc) as well, e.g.
public static void Foo()
{
Console.WriteLine("Hello");
}
...
Foo();
(The ... is used to tell Snippy "everything under here belongs in Main".)
We've just released CShell a full featured C# REPL IDE. It supports code completion, script files, adding references and is really extensible. Also we plan to add NuGet support soon, which will make it super quick to write some code and see how it works.
http://cshell.net/
We love LINQPad but it doesn't have a REPL, the code is executed once and you cannot do anything further with the results unless you modify the script and run the whole script again. This is okey, but sometimes if you want even more a scripty feeling then to evalute your code in a REPL is really nice and convenient.
I also find that SharpDevelop is so quick and lightweight that it is the easiest way to whip off a quick test project.
You may find the Object Test Bench useful. It's not very well known, but lets you create instances of classes, execute static methods and so on. It can be useful for discovering how to use unfamiliar APIs or for quick debugging of your own classes and methods, saving the creation of a test harness for simple checks.
You can find the MSDN documentation here:
http://msdn.microsoft.com/en-us/library/c3775d98%28VS.80%29.aspx
If you could wait a while.. it looks like there could be a C# equivalent of Ruby's irb in time for C# 4.0
Anders H. demonstrated an interactive console session where you could type in arbitrary C# code and see results in his 'Future of C#' piece at PDC 2008. You could even pop a WPF Window from it and then play with it via the console interface. Pretty cool.
Use LINQPad.
Name notwithstanding, it can execute any C# or VB code, from simple expressions to entire classes.
Plus, it can visualize entire object graphs in the results.
You can even add references to your own assemblies.
Try the C# REPL Script Environment that is part of the O2 Platform. It is exactly what you are asking for.
It will give you a perfect environment to try out all C# features and APIs (conceptually the O2 REPL environment is similar to LinqPAD)
You should also take a look at Roslyn from Microsoft. On Multiple Roslyn based tools (all running Stand-Alone outside VisualStudio) , the first one is a simple Roslyn REPL
If you happen to know and like Python, then IronPython may be a good alternative. It comes with a (Python) REPL console (ipy.exe) where you can import and use all of the .Net types.
I find it useful for testing out little things, exactly like DateTime.Parse("Blah").
Note that it can't actually execute C# code, but if all you want is access to .Net, then it's perfect. Also, if you install the IronPython Tools for VS, you can start a REPL session right in VS using a single keyboard shortcut (Alt+I) and leave it running in a docked window for when you need it.
Update: http://avillenas.com/post/interactive-c
Well, you can try this.
Download and install dotnet.github.io
Open cmd
Type "dotnet repl"
Type whatever you need.
I did what you wanted to do. Click here to see the gif
The Roslyn project sources contain a REPL called CSI (http://sourceroslyn.io/#csi/Csi.cs). The Csi class is currently internal but with the the “csi” project (Roslyn.sln: Interactive/Hosts/csi) an executable console application is available that supports e. g. the command #r to load an assembly and #load to load and execute script files (start the csi and use #help).

Categories

Resources