Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

visual studio 2010 - How do I create an COM visible class in C#?

I using Visual Studio 2010 (.NET 4). I need to create a COM object (in C#) and have no idea how to get started (what type of project to use,etc.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK I found the solution and I'll write it here for the common good.

  1. Start VS2010 as administrator.
  2. Open a class library project (exmaple - MyProject).
  3. Add a new interface to the project (see example below).
  4. Add a using System.Runtime.InteropServices; to the file
  5. Add the attributes InterfaceType, Guid to the interface.
  6. You can generate a Guid using Tools->Generate GUID (option 4).
  7. Add a class that implement the interface.
  8. Add the attributes ClassInterface, Guid, ProgId to the interface.
    ProgId convention is {namespace}.{class}
  9. Under the Properties folder in the project in the AssemblyInfo file set ComVisible to true.
  10. In the project properties menu, in the build tab mark "Register for COM interop"
  11. Build the project

now you can use your COM object by using it's ProgID.

example: the C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Runtime.InteropServices;

namespace Launcher
{

    [InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")]
    public interface ILauncher
    {
        void launch();
    }

    [ClassInterface(ClassInterfaceType.None), Guid("YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYY"), ProgId("Launcher.Launcher")]
    public class Launcher : ILauncher
    {
        private string path = null;

        public void launch()
        {
            Console.WriteLine("I launch scripts for a living.");

        }

    }
}

and VB script using the COM:

set obj = createObject("PSLauncher.PSLauncher") obj.launch()

and the output will be:

I launch scripts for a living


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...