public partial class ICOperation : Form
{
// 包含所有与IC卡交互的方法
[StructLayout(LayoutKind.Sequential)]
public unsafe class ICAPI
{
// 初始化IC卡读写器
[DllImport("Mwic_32.dll", EntryPoint = "auto_init", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingCOnvention= CallingConvention.StdCall)]
public static extern int Initialize(int port, int baud);
// 设置安全模式
[DllImport("Mwic_32.dll", EntryPoint = "setsc_md", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingCOnvention= CallingConvention.StdCall)]
public static extern int SetSecurityMode(int icDevice, int mode);
// 获取设备状态
[DllImport("Mwic_32.dll", EntryPoint = "get_status", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingCOnvention= CallingConvention.StdCall)]
public static extern Int16 GetStatus(int icDevice, Int16* status);
// 关闭设备
[DllImport("Mwic_32.dll", EntryPoint = "ic_exit", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingCOnvention= CallingConvention.StdCall)]
public static extern int CloseDevice(int icDevice);
// 发出蜂鸣声
[DllImport("Mwic_32.dll", EntryPoint = "dv_beep", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingCOnvention= CallingConvention.StdCall)]
public static extern int Beep(int icDevice, int duration);
// 向IC卡写入数据
[DllImport("Mwic_32.dll", EntryPoint = "swr_4442", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingCOnvention= CallingConvention.StdCall)]
public static extern int WriteToCard(int icDevice, int offset, int length, char* data);
// 校验卡密码
[DllImport("Mwic_32.dll", EntryPoint = "csc_4442", SetLastError = true, CharSet = CharSet.Auto, ExactSpelling = true, CallingCOnvention= CallingConvention.Winapi)]
public static extern Int16 CheckCardPassword(int icDevice, int length, [MarshalAs(UnmanagedType.LPArray)] byte[] password);
}
public ICOperation()
{
InitializeComponent();
}
private void OnWriteButtonClicked(object sender, EventArgs e)
{
int icDevice = ICAPI.Initialize(0, 9600);
if (icDevice <0)
{
MessageBox.Show("端口初始化失败,请检查接口线是否连接正确。");
return;
}
int securityMode = ICAPI.SetSecurityMode(icDevice, 1);
unsafe
{
Int16 status = 0;
Int16 result = ICAPI.GetStatus(icDevice, &status);
if (result != 0)
{
MessageBox.Show("设备当前状态错误!");
ICAPI.CloseDevice(icDevice);
return;
}
if (status != 1)
{
MessageBox.Show("请插入IC卡");
ICAPI.CloseDevice(icDevice);
return;
}
}
unsafe
{
byte[] password = { 255, 255, 255 };
Int16 passwordCheckResult = ICAPI.CheckCardPassword(icDevice, 3, password);
if (passwordCheckResult <0)
{
MessageBox.Show("IC卡密码错误!");
return;
}
for (int i = 0; i {
char data = textBox1.Text[i];
int writeResult = ICAPI.WriteToCard(icDevice, 33 + i, 1, &data);
if (writeResult != 0)
{
MessageBox.Show("数据写入IC卡失败!");
ICAPI.CloseDevice(icDevice);
return;
}
}
ICAPI.Beep(icDevice, 20);
MessageBox.Show("数据已成功写入IC卡中!");
ICAPI.CloseDevice(icDevice);
}
}
private void OnExitButtonClicked(object sender, EventArgs e)
{
Application.Exit();
}
}