📄 unit1.cpp
字号:
//------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
HANDLE hComm; //将给串行端口使用的Handle声明
//------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if (hComm!=INVALID_HANDLE_VALUE) CloseHandle(hComm);
exit(EXIT_SUCCESS);
}
//------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char *ComNo;
DCB dcb;
String Temp;
//取得要打开的通信端口
Temp = "COM"+IntToStr(rdCOM->ItemIndex +1);
//转换至指针类型Char
ComNo = Temp.c_str();
hComm = CreateFile(ComNo,GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, 0);
if (hComm == INVALID_HANDLE_VALUE) // 如果COM 未打开
{
MessageBox(0, "打开通信端口错误!!","Comm Error",MB_OK);
return;
}
//将dcb地址传入,以取得通信参数
GetCommState(hComm,&dcb); // 得知目前COM 的状态
dcb.BaudRate = CBR_9600; // 设置波特率为9600
dcb.ByteSize = 8; // 字节为 8 bit
dcb.Parity = NOPARITY; // Parity 为 None
dcb.StopBits = ONESTOPBIT; // 1 个Stop bit
//通信端口设置
if (!SetCommState(hComm, &dcb)) { // 设置COM 的状态
MessageBox (0, "通信端口设置错误!!!","Set Error",MB_OK);
CloseHandle(hComm);
return;
}
}
//------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
unsigned long lStatus;
if (hComm == INVALID_HANDLE_VALUE) return;
if (GetCommModemStatus(hComm,&lStatus))
{
//检查CTS状态
if (lStatus & MS_CTS_ON)
spCTS->Brush->Color =clRed;
else spCTS->Brush->Color =clWhite;
//检查DSR状态
if (lStatus & MS_DSR_ON )
spDSR->Brush->Color =clRed;
else spDSR->Brush->Color =clWhite;
//检查RI状态
if ( lStatus & MS_RING_ON )
spRI->Brush->Color =clRed;
else spRI->Brush->Color =clWhite;
//检查CD状态
if ( lStatus & MS_RLSD_ON )
spCD->Brush->Color =clRed ;
else spCD->Brush->Color =clWhite;
}
}
//------------------------------------------------------------------
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -