How do I call Win32 API functions SetClipBoardViewer, ChangeClipboardChain, etc, from C++ .NET app ?

T

Thomas Dickens

Hi,

I am a "hobby" programmer with a lot of familiarity with pre-.NET C++
programming in Windows, but not too much with .NET. I've written a
Form based Windows application and want to set it up so that the app
monitors changes to clipboard data. Therefore, I need to call the
Win32 functions SetClipBoardViewer, etc. (Or is there another way to
do this in .NET that I haven't found)?

As far as I can tell, I need to use the P/Invoke mechanism with
declarations something like:

[DllImport("User32")]
static int SetClipboardViewer(int hWndNewViewer);

(I would think these should be HWND's, but the above is what I found.)

My problem is that I don't know the correct declarations for these
functions, and I don't know how to set up the calls to them. I found
an example for C# that shows how to do the whole process of setting up
a clipboard monitoring application, but I really want to learn how to
do this in C++.

Any help would be appreciated!
Thanks,
Tom
 
D

David Lowndes

I am a "hobby" programmer with a lot of familiarity with pre-.NET C++
programming in Windows, but not too much with .NET. I've written a
Form based Windows application and want to set it up so that the app
monitors changes to clipboard data. Therefore, I need to call the
Win32 functions SetClipBoardViewer, etc. (Or is there another way to
do this in .NET that I haven't found)?

As far as I can tell, I need to use the P/Invoke mechanism with
declarations something like:

Tom,

The beauty of using C++/CLI as your .Net language is that you often
don't need to use visible kludges like P/Invoke to call native code -
just #include the appropriate header (windows.h) as you've always
done, and write the code. Have a look at "Using C++ Interop (Implicit
PInvoke)" in MSDN.

Dave
 
T

Tamas Demjen

Thomas said:
[DllImport("User32")]
static int SetClipboardViewer(int hWndNewViewer);

(I would think these should be HWND's, but the above is what I found.)

How so? It is an HWND in the Win32 API:
http://msdn2.microsoft.com/en-us/library/ms649052.aspx

The problem with using int is that it is always a 32-bit value. HWND is
32-bit on 32-bit systems, but 64-bit on 64-bit systems. So your code is
not portable. It is a very bad idea to marshal pointers as integers,
because when the time comes to port to x64, it will crash.

I agree with David's answer, but if you must use P/Invoke, declare it
IntPtr instead of int:

[DllImport("user32.dll")]
static IntPtr SetClipboardViewer(IntPtr hWndNewViewer);

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top