很久以前就准备学习VC环境下,如何实现串口通信的。今天,胡搞瞎搞,终于迈出了第一步,成功通过串口发送信息出去,算是个人一个小小的里程牌吧。
代码如下:
//=====================================================================================
#include <windows.h>
#include <windowsx.h>
#include "main.h"
#include "dialogs.h"
#include "resource.h"
#include "stdio.h"
HANDLE hCom;
DWORD dwError;
DCB LpdcbCom;
//Compile error using LPDCB
char ScomBuf[256];
void OpenScom()
{
hCom = CreateFile( "COM7",\
GENERIC_READ | GENERIC_WRITE,\
0,\
NULL,\
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,\
NULL
);
if( hCom == INVALID_HANDLE_VALUE)
{
if( 5 == GetLastError() )
{
sprintf(ScomBuf,"%s","串口已被占用");
MessageBox(NULL,ScomBuf,NULL,MB_OK);
}
// sprintf(ScomBuf,"%u",dwError);
}
GetCommState(hCom,&LpdcbCom);
BuildCommDCB("baud=9600 parity=N data=8 stop=1",&LpdcbCom);
SetCommState(hCom,&LpdcbCom);
}
void InitScom()
{
}
BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
//BEGIN MESSAGE CRACK
HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);
HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand);
HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);
//END MESSAGE CRACK
}
return FALSE;
}
////////////////////////////////////////////////////////////////////////////////
// Main_OnInitDialog
BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
// Set app icons
HICON hIcon = LoadIcon((HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE) ,MAKEINTRESOURCE(IDI_ICONAPP));
SendMessage(hwnd, WM_SETICON, TRUE, (LPARAM)hIcon);
SendMessage(hwnd, WM_SETICON, FALSE, (LPARAM)hIcon);
//
// Add initializing code here
//
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
// Main_OnCommand
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch(id)
{
case IDC_SEND:
// MessageBox(hwnd,"TEST","TEST",MB_OK);
TransmitCommChar(hCom,'J');
break;
case IDC_OK:
// MessageBox(hwnd,TEXT("You clicked OK!"),TEXT("SCOM"),MB_OK);
OpenScom();
// EndDialog(hwnd, id);
break;
case IDC_CANCEL:
// MessageBox(hwnd,TEXT("You clicked Cancel!"),TEXT("SCOM"),MB_OK);
CloseHandle(hCom);
// EndDialog(hwnd, id);
break;
default:break;
}
}
////////////////////////////////////////////////////////////////////////////////
// Main_OnClose
void Main_OnClose(HWND hwnd)
{
EndDialog(hwnd, 0);
}
//End of file
//=====================================================================================
其中有些问题,暂时想不明白,原来代码中第11行使用的是这个段“LPDCB LpdcbCom;",并且将“GetCommState(hCom,&LpdcbCom);”这个段和其后的两个段中的”&LpdcbCom“改为”LpdcbCom“,但是程序运行之后,打开串口时就会报错。
后来,照着教程,将段改为现在的版本“LPDCB LpdcbCom;”,就没问题了。
这是为什么呢?