?? 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 + -