dotnet thoughts 

a dotnet developer's technical blog

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

  1. 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.
  2. 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 :)

Loading Image from URL in Windows Forms

Recently I got a chance to work on Windows Application, it is Twitter client using C#. In that I need to show some Image from a URL. I thought like Microsoft will provide some way to load Images from URL and I tried to do the same with “Image.FromFile” method. But it failed. :( Then I searched and found it will not supports Urls. So I developed an extention method for Image class, which will load from URL. I tried to Inherit from Image class, but that doesn’t work, it is not inheritable. :(

And here is the code

namespace dotnetthoughts
{
	public static class Utilities
	{
		public static Image FromURL(this Image image, string Url)
		{
			HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
			HttpWebResponse respone = request.GetResponse() as HttpWebResponse;
			return Image.FromStream(respone.GetResponseStream(),true);
		}
		public static Image FromURL(this Image image, string Url, string userName, string Password)
		{
			HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
			request.Credentials = new NetworkCredential(userName, Password);
			HttpWebResponse respone = request.GetResponse() as HttpWebResponse;
			return Image.FromStream(respone.GetResponseStream(), true);
		}
	}
}

In the second method, I am accepting the Username and Password, so it can access protected Images too.

Implementation of this code

//If we don't put null, C Sharp compiler will not allows to compile the application
Image img = null;
this.pictureBox1.Image = img.FromURL(this.textBox1.Text);

Gridsplitter control in WPF

Sorry for a long delay in the post. I changed my project again. Now I am back to WPF and .Net 3.5.  While exploring WPF, I come to a situation where I need to create a UI like windows explorer. I managed it with Treeview control in left side and ListView in the right side. Also I put a Gridsplitter(I thought it is equivalant to Splitter control in Windows Forms). And everything works fine, except the GridSplitter, I was able to see that but its not draggable. After doing some searching, I found one solution, same applicable for Horizontel splitter too.

Here is the XAML.

<grid>
<grid.RowDefinitions>
<rowDefinition Height="*"/>
<rowDefinition Height="3"/>
<rowDefinition Height="*"/>
</grid.RowDefinitions>
<treeView Grid.Row="0">
</treeView>
<treeView Grid.Row="2">
</treeView>
<gridSplitter Grid.Row="1" HorizontalAlignment="Stretch" />
</grid>

The trick in the HorizontalAlignment attribute. And if you want to Vertical split you need to apply strech for VerticalAlignment attribute.

Image viewer in WPF

In my blog you can find few postings about Image viewer application in WPF. This is a project I am currently doing to learn WPF. I have updated the source code, with some new features

  1. Resources strings
  2. Keyboard shortcuts
  3. File Information
  4. Custom commands
  5. Addressbar using dropdownlist

etc.

If you wish you can download the source from here

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
    &lt;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

        &lt;DllImport("shell32.dll")gt; _
        Public Shared Function ShellExecuteEx(&lt;[In](), Out()&gt; _
      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.

« Newer PostsOlder Posts »