Consuming a C++ DLL in C#
While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn’t get any code for the implementation. So I done some searching and I found a solution. It is not a complete solution, but it works
Creating a DLL using C++
For creating a DLL in C++, I was used cl.exe, which comes with .net framework. For the implementation I just wrote simple C++ file.(Simple.cpp)
#include <iostream>
extern "C" __declspec(dllexport) char* Hello();
char* Hello()
{
return "Hello world";
}
I think this is pretty much clear.The extern “C” __declspec(dllexport) allows generate export names automatically. For more details :Exporting from a DLL Using __declspec(dllexport)(MSDN)
After creating this Simple.cpp file, go to Visual Studio Tools > Visual Studio 2008 Command Prompt. Go to the location where you have stored the Simple.cpp file and for compiling and linking C++ file you can use “cl.exe /LD Simple.cpp”.(For more details about cl.exe options checkout : Compiler Options Listed Alphabetically(MSDN) It will compile and Link, and gives a DLL as output.
Consuming a C++ library in C#
When I try to add the DLL by Add Reference, Visual Studio will not allows to add C++ library as Reference. So I tried it with Interop option, by using DLLImportAttribute.
[DllImport(@"D:\Simple.dll", EntryPoint = "Hello")] public extern static string Hello();
Then you can call this function in C# like the following
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(Hello());
}
It will display a Messagebox with “Hello World”. Thats it you consumed a C++ DLL in C#.
Issue in the implementation
- I can’t use the DllImport function without the full location. To avoid this I tried to Register the DLL using RegSvr32.But I got some error from RegSvr like this.
The module “D:\Simple.dll” was loaded but the entry-point DllRegisterServer was not found.
Make sure that “D:\Simple.dll” is a valid DLL or OCX file and then try again.
I still exploring the things, I will update once I got the solution for this. Happy Coding
Disable autorun of USB disks
In the last post I was implemented the USB detection, but the problem become more complex, because my USB stick contains some Autorun.inf file and when you plug the stick, it start executing some program, otherwise you need to cancel it explicity. The client need to avoid this. So I have to find some solution, where, I need to disable the autorun, when my program is running. Luckly, on the first search in google only, I got the solution.
Here is the implementation.
'API
Public QueryCancelAutoPlay As Integer = 0
Public Shared Function RegisterWindowMessage(ByVal strMessage As String) As Integer
'No implementation required.
End Function
'Modified implementation of WndProc() method
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If QueryCancelAutoPlay = 0 Then
QueryCancelAutoPlay = RegisterWindowMessage("QueryCancelAutoPlay")
End If
If m.Msg = WM_DEVICECHANGE Then
Select Case m.WParam
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEARRIVAL
lblMessage.Text = "USB Inserted"
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEREMOVECOMPLETE
lblMessage.Text = "USB Removed"
End Select
ElseIf m.Msg = QueryCancelAutoPlay Then
m.Result = CType(1, IntPtr)
Return
End If
MyBase.WndProc(m)
End Sub
I implemented it in C#, and I re-wrote it in VB.Net, and I didn’t tested it
If you are facing any issues, let me know.
How to detect USB insertion and removal in VB.Net
Recently I moved to a Desktop application development team, where I have to look for the insertion of the USB. I need to read the contents of the USB drive and updates the application. I got a lot of solutions from Google to detect the USB insertion and removal. I am posting the easiest one I found, it is VB.Net, but I don’t think we can use it Class Libraries, and we may need to use the Windows Forms.
Private WM_DEVICECHANGE As Integer = &H219
Public Enum WM_DEVICECHANGE_WPPARAMS As Integer
DBT_CONFIGCHANGECANCELED = &H19
DBT_CONFIGCHANGED = &H18
DBT_CUSTOMEVENT = &H8006
DBT_DEVICEARRIVAL = &H8000
DBT_DEVICEQUERYREMOVE = &H8001
DBT_DEVICEQUERYREMOVEFAILED = &H8002
DBT_DEVICEREMOVECOMPLETE = &H8004
DBT_DEVICEREMOVEPENDING = &H8003
DBT_DEVICETYPESPECIFIC = &H8005
DBT_DEVNODES_CHANGED = &H7
DBT_QUERYCHANGECONFIG = &H17
DBT_USERDEFINED = &HFFFF
End Enum
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_DEVICECHANGE Then
Select Case m.WParam
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEARRIVAL
lblMessage.Text = "USB Inserted"
Case WM_DEVICECHANGE_WPPARAMS.DBT_DEVICEREMOVECOMPLETE
lblMessage.Text = "USB Removed"
End Select
End If
MyBase.WndProc(m)
End Sub
The code is pretty clear; I am overriding the WndProc method. When a USB inserted or removed, Windows will send some message (WM_DEVICECHANGE) to all the applications. And the WParam property of that message will contains the details of the device event. The system broadcasts the DBT_DEVICEARRIVAL device event when a device or piece of media has been inserted and becomes available. The system broadcasts the DBT_DEVICEREMOVECOMPLETE device event when a device or piece of media has been physically removed.
Now I am looking into how can remove a USB programmatically.
File Properties Dialog box using VB.Net
While working with my WPF project, I come to a requirement, where I need to display the File Properties dialog box, which available on right click on a File > selecting Properties. I got one solution from Google groups, but I forgot the link.
I am posting the code.
Imports System
Imports System.Runtime.InteropServices
Namespace Win32
<StructLayout(LayoutKind.Sequential)gt; _
Public Class SHELLEXECUTEINFO
Public cbSize As Integer
Public fMask As Integer
Public hwnd As IntPtr
Public lpVerb As String
Public lpFile As String
Public lpParameters As String
Public lpDirectory As String
Public nShow As Integer
Public hInstApp As Integer
Public lpIDList As Integer
Public lpClass As String
Public hkeyClass As Integer
Public dwHotKey As Integer
Public hIcon As Integer
Public hProcess As Integer
End Class
Public Class Shell
Public Const SEE_MASK_INVOKEIDLIST As Integer = 12
<DllImport("shell32.dll")gt; _
Public Shared Function ShellExecuteEx(<[In](), Out()> _
ByVal execInfo As SHELLEXECUTEINFO) As Boolean
End Function
End Class
End Namespace
And you can call the function like this
Dim fileInfo As New Win32.SHELLEXECUTEINFO
fileInfo.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(fileInfo)
fileInfo.lpVerb = "properties"
fileInfo.fMask = Win32.Shell.SEE_MASK_INVOKEIDLIST
fileInfo.nShow = 1
fileInfo.lpFile = filename 'File name to display properties.
Win32.Shell.ShellExecuteEx(fileInfo)
There is one issue I am facing right now with the code, the Dialog is not displayed as Modal window. I have to do R&D on it, and will update later.