int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
MSG msg;
char host[VALUE_LENTH_MAX];
char username[VALUE_LENTH_MAX];
char password[VALUE_LENTH_MAX];
char db_name[VALUE_LENTH_MAX];
FILE *init;
init = fopen("Init.txt", "r");
if (init == NULL)
{
init = fopen("Init.txt", "w");
fprintf(init, "host\t%s\nusername\t%s\npassword\t%s\ndatabase\t%s", "set", "set", "set", "set");
fclose(init);
MessageBoxEx(NULL, TEXT("请检查配置文件"), "查找配置文件失败", MB_ICONERROR | MB_TOPMOST, 0);
PostQuitMessage(0);
}
fscanf(init, "host\t%s\nusername\t%s\npassword\t%s\ndatabase\t%s", host, username, password, db_name);
fclose(init);
mysql_init(&mysql);
if (!mysql_real_connect(&mysql, host, username, password, db_name, 0, NULL, 0))
{
MessageBox(NULL, TEXT("数据库连接失败,请重新设定配置文件参数"), "错误", MB_ICONERROR);
return 0;
}
g_hInstance = hInstance;
DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, LoginDlgProc);
while (TRUE)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
//--------------------------------------------------------------创建登录对话框
BOOL CALLBACK LoginDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
TCHAR name[VALUE_LENTH_MAX];
TCHAR pwd[VALUE_LENTH_MAX];
TCHAR sql[SQL_LENTH_MAX];
switch (message)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_BTN_LOGIN:
GetWindowText(GetDlgItem(hDlg, IDC_EDIT1), name, VALUE_LENTH_MAX);
GetWindowText(GetDlgItem(hDlg, IDC_EDIT2), pwd, VALUE_LENTH_MAX);
sprintf(sql, "select * from tb_operators where name='%s' and password='%s'", name, pwd);
mysql_query(&mysql, sql);
if (mysql_errno(&mysql))
{
MessageBox(NULL, TEXT("操作失败"), "错误",MB_ICONERROR);
PostQuitMessage(0);
}
result = mysql_store_result(&mysql);
if (mysql_num_rows(result))
{
//登陆成功
EndDialog(hDlg, 0);
row = mysql_fetch_row(result);
sprintf(g_operator, "%s", row[NAME_COLUMN]); //将当前操作员的名字存入g_operator中
g_level = row[LEVEL_COLUMN];
ShowWindow(CreateDialog(g_hInstance, MAKEINTRESOURCE(ID_DLG_CLIENT), NULL, ClientDlgProc), SW_SHOW);
}
else
{
//登录错误,弹出信息
MessageBox(NULL, TEXT("登录名或密码错误"), TEXT("登陆失败"), MB_ICONERROR);
return 0;
}
mysql_free_result(result);
mysql_query(&mysql, "set names gbk"); //设置MYSQL字符集,以防乱码
break;
case IDC_BTN_CANCEL:
EndDialog(hDlg, 0);
PostQuitMessage(0);
break;
}
return TRUE;
break;
case WM_CLOSE:
PostQuitMessage(0);
case WM_DESTROY:
break;
return 0;
}
return 0;
}
这里遇到的问题是系统总是说输入密码有误,经过反复调试发现直接把密码和用户名填入select语句不经过GetWindowText读取static text里的文本的时候它是可以正确登录的,然后在点提交的时候把static text里面的文本用messagebox显示出来以后发现是乱码,在将于是在name,password的定义类型修改成TCHAR以及LPCTSTR之后都没有效果后,在项目属性中修改了字符集:项目>属性>常规>字符集中修改成了使用多字节字符集之后解决了登录的问题。
但是还有一个问题存在,那就是即使能正确读取static text里面的值,但是messagebox中显示的依旧是乱码,这个问题找到解决方法后,还会来追记的。