C#寫COM組件,JS調用控制項

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   os   檔案   io   

1、c#2005中建立項目,類型為類庫,項目名為AddCom確定。

  配置:右鍵點擊方案總管中的AddCom,選擇“屬性”,選擇“產生”,選擇“為COM Interop註冊(_P)”

2、開啟AssemblyInfo.cs檔案,設定[assembly: ComVisible(true)],如果不改則不能被其他程式調用

3、編寫com組件會用到guid(全球唯一ID),編寫com組件必須要用到。c#會預設產生一個放在AssemblyInfo.cs,如沒有產生,網上下一個產生guid的軟體,有很多呢。

4、c#中原始碼如下,按如下方法編寫代碼後產生工程,/bin/release中得到AddCom.dll。

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace AddCom
{

[Guid("298D881C-E2A3-4638-B872-73EADE25511C")]
public interface AddComInterface
{
[DispId(1)]
int iadd(int a, int b);
}

[Guid("2C5B7580-4038-4d90-BABD-8B83FCE5A467")]
[ClassInterface(ClassInterfaceType.None)]

public class AddComService : AddComInterface
{
public AddComService()
{
}
public int iadd(int a, int b)
{
int c = 0;
c = a + b;
return c;
}
}
}

5、dos下利用 e:\regasm AddCom.dll 命令註冊com組件,可以理解為非.net平台下的regsvr32註冊dll組件。提示註冊成功即可。

regasm.exe一般存在C:\Windows\Microsoft.NET\Framework\v2.0.50727 ,如果提示不是命令符的話

C:\Windows\Microsoft.NET\Framework\v2.0.50727 \regasm   D:\test.dll  ( D:\test.dll 為dll所在目錄)

 

js調用com

<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><OBJECT classid=CLSID:0045EA0A-2042-43F8-A2F4-B5CF54D45C10 id=COMTest width=0 height=0></OBJECT><script language="JavaScript"> alert("----------------------start-----------------------");var wmp;var iResult = 12345;alert(iResult);wmp = document.getElementById("ComTest"); alert(wmp );if(wmp == null){    alert(wmp );}else{    iResult = wmp.iadd(4,9);    alert("Test Successful!");}alert("iadd(4,9) =" + iResult);alert("----------------------start-----------------------");</script></head></html>

如果需要js調用新方法,需要在介面裡定義後,再在類裡實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.