如何在C#中创建ActiveX控件(COM)? [英] How do I create an ActiveX control (COM) in C#?
问题描述
我正在尝试创建一个ActiveX控件。我使用视觉工作室 2010 (.NET 4)。我需要创建 COM 对象(在C#中),并且不知道如何开始使用要使用的项目类型等)
OK我找到了解决方案,
- 以管理员身份启动VS2010。
- 打开类库项目(exmaple - MyProject)。
- 向项目添加新界面(请参见下面的示例)。
- 使用System.Runtime.InteropServices; 添加到文件
- 添加属性InterfaceType,Guid到接口。
- 您可以使用工具 - >生成GUID(选项4)生成Guid。
- 添加实现接口的类。
- 将属性ClassInterface,Guid和ProgId添加到界面。
ProgId约定是{namespace}。{class}
- 在AssemblyInfo文件中项目的Properties文件夹下将ComVisible设置为true。
- 在项目属性菜单中,在构建选项卡中标记注册COM互操作
- 构建项目
例如:
C#代码:
现在你可以使用它的ProgID来使用你的COM对象。 p>
使用System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
使用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。
}
}
}
和VB脚本使用COM:
set obj = createObject(PSLauncher.PSLauncher)
obj .launch()
,输出将是:
我为生活启动脚本
I am trying to create an ActiveX control. 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.)
OK I found the solution and I'll write it here for the common good.
- Start VS2010 as administrator.
- Open a class library project (exmaple - MyProject).
- Add a new interface to the project (see example below).
- Add a
using System.Runtime.InteropServices;
to the file - Add the attributes InterfaceType, Guid to the interface.
- You can generate a Guid using Tools->Generate GUID (option 4).
- Add a class that implement the interface.
- Add the attributes ClassInterface, Guid, ProgId to the interface.
ProgId convention is {namespace}.{class} - Under the Properties folder in the project in the AssemblyInfo file set ComVisible to true.
- In the project properties menu, in the build tab mark "Register for COM interop"
- 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
这篇关于如何在C#中创建ActiveX控件(COM)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!