Visual studio 2010 如何在C#中创建COM可见类?

Visual studio 2010 如何在C#中创建COM可见类?,visual-studio-2010,c#-4.0,com,Visual Studio 2010,C# 4.0,Com,我正在使用(.net4)。我需要创建一个对象(用C#)但不知道如何开始(使用什么类型的项目等)您可以使用类库项目。使用将作为COM对象公开的方法声明类型 确保已使部件COM可见: 并最终使用以下方式进行注册: 现在,程序集作为COM对象公开,并且您声明的类型可以被任何支持COM的客户端使用。好的,我找到了解决方案,为了公共利益,我将把它写在这里 以管理员身份启动VS2010 打开类库项目(exmaple-MyProject) 将新接口添加到项目中(请参见下面的示例) 使用System.Runt

我正在使用(.net4)。我需要创建一个对象(用C#)但不知道如何开始(使用什么类型的项目等)

您可以使用类库项目。使用将作为COM对象公开的方法声明类型

确保已使部件COM可见:

并最终使用以下方式进行注册:


现在,程序集作为COM对象公开,并且您声明的类型可以被任何支持COM的客户端使用。

好的,我找到了解决方案,为了公共利益,我将把它写在这里

  • 以管理员身份启动VS2010
  • 打开类库项目(exmaple-MyProject)
  • 将新接口添加到项目中(请参见下面的示例)
  • 使用System.Runtime.InteropServices添加
    到该文件
    
  • 将属性InterfaceType、Guid添加到接口
  • 您可以使用工具->生成Guid(选项4)生成Guid
  • 添加一个实现接口的类
  • 将属性ClassInterface、Guid、ProgId添加到接口。
    ProgId约定为{namespace}.{class}
  • 在AssemblyInfo文件中项目的Properties文件夹下,将ComVisible设置为true。
  • 在“项目属性”菜单的“生成”选项卡中,标记“为COM互操作注册”
  • 建设项目 现在,您可以通过使用COM对象的ProgID来使用它

    例如: C#代码:

    和使用COM的VB脚本:

    
    set obj=createObject(“PSLauncher.PSLauncher”)
    目标发射()
    

    输出将是:


    我启动脚本谋生

    创建步骤

  • 以管理员身份启动VisualStudio2013
  • 安装Visual Studio扩展
  • 创建类库项目(WinFormActivex)
  • 创建示例窗口窗体(主窗口)
  • 创建新的组件接口(ILauncher)
  • 创建新的安全接口(IObjectSafety)
  • 创建实现接口并启动窗口的组件控件(启动器)
  • 检查所有guid是否由您生成
  • 检查项目是否标记为COM
  • 使用WinFormActivex的主输出创建安装项目(LauncherInstaller),属性为
    Register=vsdrpCOM
  • 安装启动器安装程序
  • 在浏览器中运行测试页面(test.html)
  • 主窗口 您可以创建一个普通表单,这里是预生成的

    public partial class MainWindow : Form
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
    
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    
        #region Windows Form Designer generated code
    
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(42, 23);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 20);
            this.textBox1.TabIndex = 0;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(42, 65);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(100, 20);
            this.textBox2.TabIndex = 0;
            //
            // MainWindow
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Name = "MainWindow";
            this.Text = "MainWindow";
            this.ResumeLayout(false);
            this.PerformLayout();
    
        }
    
        #endregion
    
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
    }
    
    IObjectSafety

    [ComImport()]
    [Guid("51105418-2E5C-4667-BFD6-50C71C5FD15C")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IObjectSafety
    {
        [PreserveSig()]
        int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions);
        [PreserveSig()]
        int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions);
        }
    
    启动器 请在此处生成您的GUID

     [ComVisible(true)]
     [ClassInterface(ClassInterfaceType.None)]
     [Guid("D100C392-030A-411C-92B6-4DBE9AC7AA5A")]
     [ProgId("WinFormActivex.Launcher")]
     [ComDefaultInterface(typeof(ILauncher))]
     public class Launcher : UserControl, ILauncher, IObjectSafety
     {
         #region [ ILauncher ]
    
         public void ShowWindow()
         {
             var f = new MainWindow();
             f.StartPosition = FormStartPosition.Manual;
             f.Location = Screen.AllScreens[0].Bounds.Location;
             f.WindowState = FormWindowState.Normal;
             f.WindowState = FormWindowState.Maximized;
             f.ShowInTaskbar = false;
             f.Show();
         }
    
         #endregion
    
         #region [ IObjectSafety ]
    
         public enum ObjectSafetyOptions
         {
             INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001,
             INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002,
             INTERFACE_USES_DISPEX = 0x00000004,
             INTERFACE_USES_SECURITY_MANAGER = 0x00000008
         };
    
         public int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions)
         {
             ObjectSafetyOptions m_options = ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_CALLER | ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_DATA;
             pdwSupportedOptions = (int)m_options;
             pdwEnabledOptions = (int)m_options;
             return 0;
         }
    
         public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
         {
             return 0;
         }
    
         #endregion
     }
    
    test.html 请检查您的CLSID是否与(启动器)GUID匹配

    
    var x=新的ActiveXObject(“WinFormActivex.Launcher”);
    警报(x.GetText());
    
    参考资料


    如果有人知道如何在C#中创建COM,那我就不必是ActiveX了started@Bujutsu然而,ActiveX部分的信息将更难找到:简单的WinForms得到了广泛的演示。@Richard关于我的回答的一个独特之处是,我为windows窗体安全ActiveX提供了明确而全面的完整解决方案。另一个不那么容易的区别是链接答案的不同IDE,它是针对VisualStudio2010的。谢谢你的评论。如果有人还需要帮助,这个链接是一个很好的开始:“用将作为COM对象公开的方法声明一个类型”?我是否必须明确地实现一个接口并给它一个GUID,或者“使Assem.COM可见”选项就是这样?我也不理解这一点。您所说的“使用将作为COM对象公开的方法声明类型”是什么意思?此外,如果您构建了程序集并且在使用它时遇到问题:(“无法创建对象”错误)我遵循了上述步骤,我的宏如下Sub test()Dim ob as object Set ob=CreateObject(“ClassCom.Name”)Dim name As String name=ob.launc()End Sub它说“Error 429”activex无法创建对象可能出了什么问题?我遵循了相同的方法,但没有运气。使用VB.NetSample VB.Net代码在远程计算机中启动exe时,Activex无法创建相同的错误:受保护的未命名子对象1\u单击(作为对象的发件人,作为事件参数)Dim stremoteserver=“xxxxx”Dim strUser=“xxx”Dim strPassword=“yyy”Dim strCommand strCommand=”“Dim objWMIService=GetObject(“winmgmts:&”{impersonationlevel=impersonate}!\\“&strRemoteServer&“\root\cimv2”)Dim objProcess=objWMIService.Get(“Win32\U进程”)Dim objQWCreate=objProcess.Create(strCommand)End子错误:“无法创建ActiveX组件。”
    using System.Runtime.InteropServices;
    namespace WinFormActivex
    {
        [ComVisible(true)]
        [InterfaceType(ComInterfaceType.InterfaceIsDual)]
        [Guid("94D26775-05E0-4B9C-BC73-C06FE915CF89")]
        public interface ILauncher
        {
            void ShowWindow();
        }
    }
    
    [ComImport()]
    [Guid("51105418-2E5C-4667-BFD6-50C71C5FD15C")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IObjectSafety
    {
        [PreserveSig()]
        int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions);
        [PreserveSig()]
        int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions);
        }
    
     [ComVisible(true)]
     [ClassInterface(ClassInterfaceType.None)]
     [Guid("D100C392-030A-411C-92B6-4DBE9AC7AA5A")]
     [ProgId("WinFormActivex.Launcher")]
     [ComDefaultInterface(typeof(ILauncher))]
     public class Launcher : UserControl, ILauncher, IObjectSafety
     {
         #region [ ILauncher ]
    
         public void ShowWindow()
         {
             var f = new MainWindow();
             f.StartPosition = FormStartPosition.Manual;
             f.Location = Screen.AllScreens[0].Bounds.Location;
             f.WindowState = FormWindowState.Normal;
             f.WindowState = FormWindowState.Maximized;
             f.ShowInTaskbar = false;
             f.Show();
         }
    
         #endregion
    
         #region [ IObjectSafety ]
    
         public enum ObjectSafetyOptions
         {
             INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001,
             INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002,
             INTERFACE_USES_DISPEX = 0x00000004,
             INTERFACE_USES_SECURITY_MANAGER = 0x00000008
         };
    
         public int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions)
         {
             ObjectSafetyOptions m_options = ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_CALLER | ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_DATA;
             pdwSupportedOptions = (int)m_options;
             pdwEnabledOptions = (int)m_options;
             return 0;
         }
    
         public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
         {
             return 0;
         }
    
         #endregion
     }
    
    <html>
        <head>
            <objectname="activexLauncher" style='display:none' id='activexLauncher' classid='CLSID:D100C392-030A-411C-92B6-4DBE9AC7AA5A' codebase='WinFormActivex'></object>
          <script language="javascript">
            <!-- Load the ActiveX object  -->
            var x = new ActiveXObject("WinFormActivex.Launcher");
            alert(x.GetText());
          </script>
        </head>
        <body>
        </body>
    </html>