雖然微軟不鼓勵 .NET 直接呼叫 ActiveX,但在特定舊系統整合情境下仍有需求。本文示範以 C# 建立 ActiveX 控制項(.dll),並在網頁中透過 <OBJECT> 標籤嵌入、透過 JavaScript 呼叫其屬性與方法。
ActiveXDotNet)。UserControl(例:AbeenControl),拖放 Label、Button、GroupBox。AssemblyInfo.cs 加入權限屬性,允許部分信任呼叫者:using System.Security;
[assembly: AllowPartiallyTrustedCallers()]
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace ActiveXDotNet
{
public class AbeenControl : UserControl
{
private Label label1;
private Button button1;
private GroupBox groupBox1;
private Container components = null;
public string LabelText
{
get => label1.Text;
set => label1.Text = value;
}
public AbeenControl() => InitializeComponent();
private void InitializeComponent()
{
this.label1 = new Label();
this.button1 = new Button();
this.groupBox1 = new GroupBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
// label1
this.label1.Location = new System.Drawing.Point(16, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(296, 23);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
// button1
this.button1.Location = new System.Drawing.Point(120, 56);
this.button1.Name = "button1";
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.Click += button1_Click;
// groupBox1
this.groupBox1.Controls.AddRange(new Control[] { label1, button1 });
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(320, 88);
this.groupBox1.TabIndex = 2;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
// AbeenControl
this.Controls.Add(this.groupBox1);
this.Name = "AbeenControl";
this.Size = new System.Drawing.Size(328, 96);
this.Load += AbeenControl_Load;
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "點擊完成!";
}
private void AbeenControl_Load(object sender, EventArgs e) { }
protected override void Dispose(bool disposing)
{
if (disposing && components != null) components.Dispose();
base.Dispose(disposing);
}
}
}
ActiveXDotNet.dll。https://localhost/WebApplication1/)。
<html>
<head><title>Test ActiveX</title></head>
<body>
<object id="MyControl1"
classid="https://localhost/WebApplication1/ActiveXDotNet.dll#ActiveXDotNet.AbeenControl"
width="288" height="72" VIEWASTEXT>
</object>
<form id="frm" name="frm">
<input type="text" name="txt" value="請輸入資料:" id="Text1">
<input type="button" value="確定" id="Button1" name="Button1">
</form>
<script type="text/javascript">
function DoScript() {
MyControl1.LabelText = frm.txt.value;
}
</script>
</body>
</html>
AllowPartiallyTrustedCallers 降低安全性,僅在受控內網環境使用。