C#编写客户端AcitveX控件
因为项目需要在客户端进行磁卡的读取,通过卡号进行系统的登录。所以需要在客户端通过串口进行读取。
参考的有:1、微软的MSCOMM32控件2、注册的dll控件。http://www.cnblogs.com/yilin/archive/2009/09/15/1567332.html
下面是我采取的不注册dll的方法。
1、VS下新建一个dll工程。并修改工程的属性。
2、编写dll部分代码
[ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(ISerialCtrlCOMEvents))]
public class SerialReadClass : System.Windows.Forms.UserControl, ISerialCtrlCOMIncoming
{
public delegate void DataReceivedHandler();
public event DataReceivedHandler DataRecived;
private System.IO.Ports.SerialPort serialPort1;
public string Result;
public SerialReadClass()
{
InitializeComponent();
serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
OpenPort("Com1", "9600");
}
private void OpenPort(string ComName, string BaudRate)
{
serialPort1.BaudRate = Convert.ToInt32(BaudRate);
serialPort1.PortName = ComName;
try
{
if (!serialPort1.IsOpen)
{
serialPort1.Open();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] inputData = new byte[serialPort1.BytesToRead];
serialPort1.Read(inputData, 0, inputData.Length);
readString = Encoding.Default.GetString(inputData);
this.Invoke(new ControlErrorHandler(ControlError));
}
/// <summary>
/// Source interface for hooking up to COM events so that JScript/VBScript can sink event
/// handlers with us. Disgusting, but it works.
/// </summary>
[Guid("B0026756-20BD-4dfe-9E92-88D69EEB2970")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISerialCtrlCOMEvents
{
[DispId(0x60020000)]
void DataReceived();
}
/// <summary>
/// Default incoming interface for our control. Required when using COM-style events,
/// otherwise IE will no longer be able to access our public properties and methods.
/// </summary>
public interface ISerialCtrlCOMIncoming
{
string Result{get;}
}
3、web客户端部分
<object id="SerialRead" classid="SerialRead.dll#SerialRead.SerialReadClass" height="0" width="0">
</object>
<script for="SerialRead" event="ControlError">
alert(document.getElementById("SerialRead").Result);
</script>
4、说明
dll部分要通过接口公开可以订阅的事件和属性,在串口类里实现。客户端可以调用事件和获取属性值。
可是在调用dll的公开方法时,却无法直接调用,总是提示未定义该方法。