日期:2014-05-18  浏览次数:20733 次

Delphi用SPCOMM组件与串口交互的代码如何转换为C#
想用C#和serialPort实现
Delphi代码如下(代码有精简):
Delphi(Pascal) code
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, jpeg, ExtCtrls, DB, ADODB, SPComm, StdCtrls, Grids,
  DBGrids, ComCtrls, ToolWin, Buttons;

type
  TFormMain = class(TForm)
var
  FormMain: TFormMain;
  checkSumData:array[0..100] of byte;
procedure TFormMain.Button8Click(Sender: TObject);
var
    checkSumValue : integer;
    strCmd: string;
begin
    checkSumData[0] := $A0;
    checkSumData[1] := $03;
    checkSumData[2] := strtoint(EditReaderID.text);
    checkSumData[3] := $08;
    checkSumValue := CheckSum(4);

    strCmd:= 'A0 03 ' + inttoHex(checkSumData[2],2) + ' 08 ' + inttoHex(checkSumValue,2);
    SendHex(strCmd);
end;

//计算校验和的值
function CheckSum(uBuffLen : Byte ): Byte;
var
    uSum: Byte;
    i: Byte;
begin
    uSum := 0;
    i := 0;
    for i:=0 to (uBuffLen - 1) do
        uSum := uSum + checkSumData[i];
    uSum := (Not uSum) + 1;
    result:= uSum;
end;

//将string转换成16进制数发送
function SendHex(S: String): integer;
var
    s2:string;
    buf1:array[0..50000] of char;
    i:integer;
begin
    s2:='';
    for i:=1 to  length(s) do
    begin
        if ((copy(s,i,1)>='0') and (copy(s,i,1)<='9'))or((copy(s,i,1)>='a') and (copy(s,i,1)<='f'))
            or((copy(s,i,1)>='A') and (copy(s,i,1)<='F')) then
            begin
                s2:=s2+copy(s,i,1);
            end;
    end;
    for i:=0 to (length(s2) div 2-1) do
        buf1[i]:=char(strtoint('$'+copy(s2,i*2+1,2)));
        FormMain.Comm.WriteCommData(buf1,(length(s2) div 2));
end;


------解决方案--------------------
转什么转,c#有自己的串口组件 SerialPort