1. 程式人生 > >c# Activex開發之HelloWorld

c# Activex開發之HelloWorld

ring org pan true orm doc 文本 用戶控件 ces

最近需要在Web上使用WinFrom程序,所以要用到Activex技術將WinFrom程序變成插件在Web運行

一、創建用戶控件

1.1 新建用戶控件項目

技術分享

1.2 在界面上拉一個label,Text賦值為“HelloWorld”

技術分享

1.3 加上guid

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace HelloWorld
{
    [Guid("ce85468b-7742-4279-b081-2eca51a2afbc")]
    public partial class Demo : UserControl, IObjectSafety
    {
        public Demo()
        {
            InitializeComponent();
        }
    }
}

  

二. 新建安裝項目

2.1 命名:HelloWorld.Setup

技術分享

2.2 將HelloWorld.dll加進來

技術分享

2.3 雙擊HelloWorld.Setup.msi安裝即可

技術分享

技術分享

三、 新建Index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
</head>
<body>
    <div>
        <object id="demo" classid="clsid:ce85468b-7742-4279-b081-2eca51a2afbc
" width="300" height="200" /> </div> </body> </html>

3.1 註意紅色部分,這個clsid即是用戶控件的guid

3.2 運行Index.html

技術分享

四、添加自定義方法和按鈕功能

4.1 上邊的功能太簡單,我們稍微深入一點,添加一個方法給js代碼調用,在Demo.cs中加上下邊代碼

        public string SayHello()
        {
            return "Hello World";
        }

4.2 新增一個按鈕,打開文本框

技術分享

4.3 按鈕單擊事件

        private void button1_Click(object sender, EventArgs e)
        {
            Process.Start("notepad.exe");
        }

4.4 再重新編譯運行程序,然後Index.html,雙擊按鈕

技術分享

4.5 修改Index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btn1").click(function () {
                var demo = document.getElementById("demo");
                console.log(demo.SayHello());
            });
        });
    </script>
</head>
<body>
    <div>
        <input id="btn1" type="button" value="調用後臺SayHello方法" />
        <object id="demo" classid="clsid:ce85468b-7742-4279-b081-2eca51a2afbc" width="300" height="200" />
    </div>
</body>
</html>

4.6 點擊“調用後臺SayHello方法”按鈕

技術分享

OK,暫時就到這裏!

c# Activex開發之HelloWorld