CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21
  1. #1
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Question C# dll called from VB 6.0

    Hi all,
    I have one problem. I want to make a dll in C# and then call it from VB 6.0. Can anyone provide a simple example that does this: Call a function from a c# dll with "test" parameter. and the dll should open a form that has a text field on it that shows "test". If I can see how is this done then I can start all my aplication from here.

    Thank you very much!
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  2. #2
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: C# dll called from VB 6.0

    Assuming that you have knowledge of C# (I know you are good in VB 6.0, because you have helped me before), a small tutorial goes here.

    C# Project--------
    1. Open VS.NET IDE, Select New Project
    2. Select "Visual C# Projects" and Templates as "Class Library" and in the name write CallFromVB.
    3. A new Project will open with a Default Class1 in it.
    4. Copy and Paste the following Code in the Module
    Code:
    using System;
    using System.Windows.Forms;
    namespace CallFromVB
    {
     public interface iCSharpClass
     {
      int ShowForm(string sMessage);
     }
     /// <summary>
     /// 
     /// </summary>
     public class CSharpClass : iCSharpClass 
     {  
      public CSharpClass()
      {
       // Constructor is empty
      }
      #region iCSharpClass Members
      /// <summary>
      /// This function will be called from VB 6.0 
      /// and it displays the Form (Form1) with the message that was passed on from VB
      /// </summary>
      /// <param name="sMessage"></param>
      /// <returns></returns>
      public int ShowForm(string sMessage) 
      {
       //instantiate a Form Object
       Form1 frmNew = new Form1();
       //Pass the message to the Label that is present on the Form
       frmNew.lblMessage.Text = sMessage;
       //Show the Form   
       frmNew.Show();   
       return 0;
      }
      #endregion
     }
    }
    5. Now Open Project Menu and Select "Add New Item"
    6. Select a Windows Form and Click Ok.
    Don't change the name of the Form.
    7. Open Form1 and Drag a Label and name it lblMessage (Change the Font if you like)
    8. Remember the Label you put on the Form has the access modifier as Private, so we will not be able to access it from the Class. To get access to it from the Class open the Code Editor for Form1 and Change the following line
    Code:
    private System.Windows.Forms.Label lblMessage;
    to
    Code:
    public System.Windows.Forms.Label lblMessage;
    9. Now as we are going to use this Component in Un-Managed code, so we need to register it for COM Interoperability. To do this open "Project Properties and under Configuration Properties Select "Build" and on the Right Hand Panel Make Register For COM InterOp as True.
    10. We are ready to build the project. Select Build Solution from Build Menu. This will create a DLL file and a Type Library in the Bin/Debug folder.

    This ends our C# Project.

    Now in VB 6.0, open a new project and open References. Browse to the Bin/Debug folder of the CallFromVB(C#) Project and select CallFromVB.tlb file

    Open Form1's Code window and write this
    Code:
    Private Sub Form_Click()
    	Dim csharpObject As CallFromVB.CSharpClass
    	Set csharpObject = New CSharpClass
    	csharpObject.ShowForm "This is from VB"
    
    End Sub
    Now run the VB Project and Click on the Form. The Form from C# will be displayed.

    Hope this small example will help you kick start your project

    To understand more about COM InterOPerability, visit msdn.microsoft.com

    I am also attaching the C# Project, but I would suggest to do it yourself once and then if you have any problems download the C# Project.
    Attached Files Attached Files

  3. #3
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    Thank you vb_the_best for your help, I found an article here: http://www.codeguru.com/Csharp/.NET/...cle.php/c6747/ but your example seems better It's easyer to follow.
    I have just two questions:
    1. What exactly happens when I click Register For COM InterOp as True? Is any code insterted in my already existing code? Or is just a flag for the compiler?
    2. Does this dll must be registered through regsvr32 if I intend to use it on another computer? In fact I have to take both the dll and the tlb with the vb executable?

    Thank you!

    P.S. I'm now learning C# cause I wanna leave VB behind so I try to migrate all my projects from VB to C#. Untill everything is migrated I wanna use dlls so the projects still work
    Last edited by vma; September 27th, 2005 at 02:22 AM.
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  4. #4
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: C# dll called from VB 6.0

    Quote Originally Posted by vma
    1. What exactly happens when I click Register For COM InterOp as True? Is any code insterted in my already existing code? Or is just a flag for the compiler?
    Register For COM Interop
    This flag indicates that this managed project(COM) will expose a COM object that will allow this COM object to communicate with the un-managed code. Actually when you set this option to true, it automatically builds a wrapper that is known as COM Callable Wrapper that allows it to communicate
    As the un-managed clients do not have capability of communicating with .NET managed COM components, so .NET builds a COM Callable wrapper and un-managed Clients use this wrapper as a Proxy to communicate with .NET object.
    Another important thing which I forgot in the previous post is that, when you use a .NET COM object in un-managed code, you need to register it in Global Assembly Cache(GAC) as a Shared Assembly. In order to register it in the GAC, you will have to sign the assembly (COM Project) with a strong name. That can be done by a utility that comes with the VS.NET.
    Open VS.NET Command Prompt, goto the Folder containing the CallFromVb Project and type
    Code:
     sn -k CallFromVB.snk
    This will generate a Strong Name Key file for the CallFromVB project.
    Now open the C# Project and open AssemblyInfo.cs and at the end of the file write this
    Code:
    [assembly: AssemblyKeyFile("..\\..\\CallFromVB.snk")]
    This will sign the assembly(project) with a strong name. Build the project and it will automatically be added to GAC and will be registered too.
    Quote Originally Posted by vma
    Does this dll must be registered through regsvr32 if I intend to use it on another computer? In fact I have to take both the dll and the tlb with the vb executable?
    I would suggest to build the Setup project from C# itself and use that project to install the DLL/TLB files. this way you don't have to register it on the target system. It automatically gets registered and is added to the Global Assembly Cache. Don't package it with VB projects. I have never done it myself.

    Quote Originally Posted by vma
    P.S. I'm now learning C# cause I wanna leave VB behind so I try to migrate all my projects from VB to C#. Untill everything is migrated I wanna use dlls so the projects still work
    This is a very nice idea. All the best

  5. #5
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    My application will not have a setup for instalation. There is a shared drive in my company and every employee has this drive mounted at the login. On this drive there will be my application and all users will start it from a shortcut to my application. So I will have to find a way to test if the dlls are registered and if not to regiter 'em. But this is another problem
    Thank you for your responses!
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  6. #6
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    Hello again,
    So I'm still not able to do something. Though my project is a lot complicated I will propose a simpler example to make the ideea. What I want is this:
    In a dll made in C# I need some structures that contain other structs inside like:
    Code:
    public struct Files
    {
    public static string BaseFile;
    public static string LocalFile;
    }
    public struct Tools
    {
    public static string Mot2Bin;
    public static string Bin2Mot;
    }
    So in fact I have about 20 structs containing at least 10 entries for each struct.
    What I want is that from VB to be able to call this dll and be able to acces any of these members also for writing and reading. In the begining all these members are initialized from an xml file but after that I should be able to change them.

    Can anyone help pls! Thank you!

    P.S. In fact what I want is from VB after I intantiate an object of the class from the DLL, when I write the name of teh object and put a dot "." to see all the structs, schoose one, put a dot again and choose a field from that struct. I should be able to set or get this field.
    Last edited by vma; October 13th, 2005 at 09:25 AM.
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  7. #7
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    Hi Shuja Ali,
    I have a question about that code you posted. What if I want to change the label after the form was created? How can I do that?
    What I did was to declare FrmNew as a class member and instatiate it in the class constructor. Than I created another methode that was going to change the label text but it gives me a runtime error
    Here is what I did:
    c#
    Code:
    namespace AutomaticDelivery
    {
    	/// <summary>
    	/// This is the public interface 
    	/// </summary>
    	public interface iDisplayProgress
    	{
    		int ShowForm(string sMessage);
    		void LblStatus(string sStatus);
    	}
    	/// <summary>
    	/// Summary description for Class1.
    	/// </summary>
    	public class CDisplayProgress
    	{
    		private frmAutomatic frmNew;
    
    		public CDisplayProgress()
    		{
    			frmAutomatic frmNew = new frmAutomatic();	
    		}
    		public int ShowForm(string sMessage)
    		{	
    			frmNew.Text = sMessage;
    			frmNew.Show();
    			return 0;
    		}
    		public void LblStatus(string sStatus)
    		{
    			frmNew.label2.Text = sStatus;
    		}
    	}
    }
    VB:
    Code:
    Dim objAuto As AutoDisplay.CDisplayProgress
    Set objAuto = New CDisplayProgress
    
    objAuto.ShowForm "title"
    
    Call objAuto.LblStatus("status")
    Thak you for your help!
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  8. #8
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    ok... sorry for that I managed to resolve it.
    I put frmAutomatic frmNew = new frmAutomatic(); in the constructor
    frmNew = new frmAutomatic(); would have been enough
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  9. #9
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: C# dll called from VB 6.0

    I was about to reply.
    Nice to see you solved the problem yourself.
    I get really happy when i see people solving there problem themselves. It just tells that people are interested in learning and they try themselves.

  10. #10
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    Hi Shuja Ali,
    here's me back with the same old problem Now it's not a problem but rather a very strange thing.
    I made my dll as you said above but removed all code refering to the interface and it still works.
    That is my entire code:
    Code:
    public class CDisplayProgress
    	{
    		private frmAutomatic frmNew;
    
    		public CDisplayProgress()
    		{
    			frmNew = new frmAutomatic();	
    		}
    		public int ShowForm(string sTitle)
    		{	
    			frmNew.Text = sTitle;
    			frmNew.Show();
    			CDeliveryIni objIni = new CDeliveryIni(@"N:\Deltools\exe\DeliveryV3_30\delivery.xml");
    			//objIni = new CDeliveryIni(@"N:\Deltools\exe\DeliveryV3_30\delivery.xml");
    			frmNew.label2.Text = objIni.Path.file1;
    			return 0;
    		}
    		public void ButtonStatus(bool bStatus)
    		{
    			frmNew.btnExit.Enabled = bStatus;
    		}
    		public void AddMessage(string sMessage)
    		{
    			frmNew.txtProgress.Text = frmNew.txtProgress.Text + sMessage + "\r\n";
    		}
    
    		public void DistroyForm()
    		{
    			frmNew.Dispose();
    		}
    	}
    I just added a reference to the tlb in vb and all functions are accesible from VB and work fine with no interface and no strong key Now I wonder will it work on other computer also?
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  11. #11
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: C# dll called from VB 6.0

    I am glad you got it working.
    However, there are few things that you mighthave observed while using the component from VB 6.0.
    Does intellisense work? Can you use Ealry binding?
    I think your answer should be no to both these questions. The reason for this is given here

    The reason a signing the assembly with a strong name is
    • Strong names guarantee name uniqueness by relying on unique key pairs. No one can generate the same assembly name that you can, because an assembly generated with one private key has a different name than an assembly generated with another private key.
    • Strong names protect the version lineage of an assembly. A strong name can ensure that no one can produce a subsequent version of your assembly. Users can be sure that a version of the assembly they are loading comes from the same publisher that created the version the application was built with.
    • Strong names provide a strong integrity check. Passing the .NET Framework security checks guarantees that the contents of the assembly have not been changed since it was built. Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate.
    And when you are installing the assembly in GAC (this is what you do when you use it out side the managed environment), MS strongly recommends that you sign the assembly with a strong name.

    Hope this explains some stuff.

  12. #12
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    OK... I see.. I was wondering why intelisense didn't work. But I thought that it is not suposed to work in VB for COM objects got from C#. Now I see. Thank you very much again. Anyway my code works From VB I call a C# dll that shows a form in which I have info got from another dll that reads the info from xml :P kinda stupid I know
    One more thing though. If I have two different projects in C# but both in the same namespace, each generating it's own dll . Is it possible and if yes is it wise to merge somehow both projects in one? So in the solution explorer to see both projects but be able to compile only one of them. In the end I will have to have about 15 dll's comunicating between them and I don't want to keep 15 different directories.
    Thank you!
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  13. #13
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: C# dll called from VB 6.0

    Quote Originally Posted by vma
    OK... I see.. I was wondering why intelisense didn't work. But I thought that it is not suposed to work in VB for COM objects got from C#. Now I see. Thank you very much again. Anyway my code works From VB I call a C# dll that shows a form in which I have info got from another dll that reads the info from xml :P kinda stupid I know
    One more thing though. If I have two different projects in C# but both in the same namespace, each generating it's own dll . Is it possible and if yes is it wise to merge somehow both projects in one? So in the solution explorer to see both projects but be able to compile only one of them. In the end I will have to have about 15 dll's comunicating between them and I don't want to keep 15 different directories.
    Thank you!
    I have never tried this before. But you could give it a try. However, I would suggest that relook at your design prior to doing this. I don't see why you would need 15 different projects/dlls to perform a task. You would need to check if you are missing something in the design part. maybe it can be done in a more simpler way.
    All the best

  14. #14
    Join Date
    Oct 2003
    Location
    Timisoara, Romania
    Posts
    460

    Re: C# dll called from VB 6.0

    It's a very huge project done in VB. I took it over for about 2 years but it was started 5 years ago. I work in an Automotive company and this soft is making all the deliveries to production lines all over the world. I'm working with comanies like BMW, Mercedes, Ford, etc.
    Now I promoted the ideea to transfer all code from VB to C# and I was given the responsability for this. Now I want to port the code in steps because I don't have 6-7 months to work only for the the new project. So for about 1 year I will try to port the program on the new design and in the same time make improvements to the old one. Dll tehnology seemed the best way for me.
    Anyway now I have everything I need so I better start working
    You liked it? Please show your gratitude and rate it!

    There is no 'patch' for stupidity.

  15. #15
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: C# dll called from VB 6.0

    Quote Originally Posted by vma
    It's a very huge project done in VB. I took it over for about 2 years but it was started 5 years ago. I work in an Automotive company and this soft is making all the deliveries to production lines all over the world. I'm working with comanies like BMW, Mercedes, Ford, etc.
    Now I promoted the ideea to transfer all code from VB to C# and I was given the responsability for this. Now I want to port the code in steps because I don't have 6-7 months to work only for the the new project. So for about 1 year I will try to port the program on the new design and in the same time make improvements to the old one. Dll tehnology seemed the best way for me.
    Anyway now I have everything I need so I better start working
    You could even try looking at web-services. WebServices are the way to go actually. Better and easier to implement. However, it would be little bit difficult to communicate to web-services from VB 6.0.
    And do well in your project. All the best

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured