Здорова господа!
Щас читаю книгу одну по С++, «программирование для windows на С/С++», пытаюсь ГУИ разбирать и там есть пример базы данных телефонных номеров с графическим интерфейсом, ну от я решил попытаться повторить то что там написано, просто сделать свою прогу. Там ничо вроде сложного нету, одно диалоговое окно, пять кнопок всего лишь, и 2 поля и одно поле список, это значит нам нужно обрабатывать 7 событий, одно поле оно будет использоваться для вывода. Хотел раньше ее сделать, но как то времени не было, в общем начинаем делать. Я тут все опишу и со скриншотами и реальным кодом этой проги, а ниже будет ссылка на скачивания exe — файла, так что можно даже будет ее протестировать. Ну все вперед.
Это кстати мое первое оконное приложение для виндовс, самое большое.
Прогу я закачаю в архиве ниже, нихочу ее сильно описывать, то как я ее создавал я записал на видео в 6 уроках, ниже можете их посмотреть.
[youtube]https://www.youtube.com/watch?v=Z4wrMspk92k[/youtube]
[youtube]https://www.youtube.com/watch?v=DQrmbbt8jqs[/youtube]
[youtube]https://www.youtube.com/watch?v=iPHbTmw6xzs[/youtube]
[youtube]https://www.youtube.com/watch?v=IWeHt7atg4g[/youtube]
[youtube]https://www.youtube.com/watch?v=S-0yH6vv3dU[/youtube]
[youtube]https://www.youtube.com/watch?v=X_lhdnEHdEY[/youtube]
файла main.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
#include <Windows.h> #include <string> using std::string; #include <vector> using std::vector; #include <fstream> using std::ofstream; #include <iostream> using std::endl; #include <regex> using std::regex; using std::regex_replace; #include "resource.h" #include "bd.h" //собственная процедура для обработки BOOL CALLBACK DlgProc(HWND, UINT, WPARAM, LPARAM); bd obj; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int ret=DialogBox(hInstance,MAKEINTRESOURCE(IDC_EXIT), NULL,(DLGPROC)DlgProc); if(ret==10) MessageBox(NULL,(LPCTSTR)"Вы нажали exit","сообщение", MB_OK|MB_ICONINFORMATION); return ret; } BOOL CALLBACK DlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_INITDIALOG: { //SendDlgItemMessage(hwnd,IDC_LIST1,LB_RESETCONTENT,0,0); vector<string> v; v=obj.GetAllElementBd(); for(int i=0;i<v.size();i++) SendDlgItemMessage(hwnd,IDC_LIST1,LB_ADDSTRING,0,(LPARAM)v[i].c_str()); return TRUE; } case WM_COMMAND: { switch (LOWORD(wParam)) { //Кнопки case IDC_SHOW_QUERY: { //1.получаем данные из поля IDC_EDIT_ADD char buf[100]; memset(buf,0,sizeof(buf)); GetDlgItemText(hwnd,IDC_EDIT_ADD,buf,sizeof(buf)); //2.получаем вектор нужных строк vector<string> v; v=obj.SearchStr(buf); //3.очищаем список while(SendDlgItemMessage(hwnd,IDC_LIST1,LB_DELETESTRING,(WPARAM)0,0)); //4.добавляем новые данные for(int i=0;i<v.size();i++) SendDlgItemMessage(hwnd,IDC_LIST1,LB_ADDSTRING,0,(LPARAM)v[i].c_str()); return TRUE; } case IDC_SHOW_ALL: { //1.очищаем список while(SendDlgItemMessage(hwnd,IDC_LIST1,LB_DELETESTRING,(WPARAM)0,0)); //2.добавляем новые элементы vector<string> v; v=obj.GetAllElementBd(); for(int i=0;i<v.size();i++) SendDlgItemMessage(hwnd,IDC_LIST1,LB_ADDSTRING,0,(LPARAM)v[i].c_str()); return TRUE; } case IDC_ADD: { //1.получаем данные из поля IDC_EDIT1 char buf[100]; memset(buf,0,sizeof(buf)); GetDlgItemText(hwnd,IDC_EDIT_ADD,buf,sizeof(buf)); if(CheckData(buf)) { //2.добавляем строку в БД obj.AddData(buf); string s=regex_replace(buf,regex("(\\w+);\\d+"),string("$1")); //3.добавляем строку в список SendDlgItemMessage(hwnd,IDC_LIST,LB_ADDSTRING,0,(LPARAM)s.c_str()); //4.очищаем само поле SetDlgItemText(hwnd,IDC_EDIT_ADD,""); } else { MessageBox(NULL, (LPCTSTR)"Данные должны быть вида\n[pupkin;38383838]", "INFO",MB_OK|MB_ICONINFORMATION); } return TRUE; } case IDC_DELETE: { char name[100]; memset(name,0,sizeof(name)); //1.узнаем позицию выделеного элемента в списке int num=SendDlgItemMessage(hwnd,IDC_LIST,LB_GETCURSEL,0,0); //2.считываем этот элемент списка SendDlgItemMessage(hwnd,IDC_LIST,LB_GETTEXT,(LPARAM)num,(WPARAM)name); //3.удалить из БД obj.DeleteStr(name); //4.удаляем запись из самого списка SendDlgItemMessage(hwnd,IDC_LIST1,LB_DELETESTRING,(WPARAM)num,0); //5.очищаем само поле SetDlgItemText(hwnd,IDC_EDIT_NUMBER,""); return TRUE; } case IDC_EXIT: EndDialog(hwnd,10); return TRUE; //поля case IDC_EDIT_ADD: return TRUE; case IDC_EDIT_NUMBER: return TRUE; case IDC_LIST: { char name[100]; memset(name,0,sizeof(name)); //1.узнаем позицию выделеного элемента в списке int num=SendDlgItemMessage(hwnd,IDC_LIST,LB_GETCURSEL,0,0); //2.считываем этот элемент списка SendDlgItemMessage(hwnd,IDC_LIST,LB_GETTEXT,(LPARAM)num,(WPARAM)name); //3.получить номер string s; s=obj.GetNumber(name); //4.записывваем элемент в поле IDC_EDIT1 SetDlgItemText(hwnd,IDC_EDIT_NUMBER,s.c_str()); return FALSE; } } } case WM_CLOSE: { EndDialog(hwnd,0); return FALSE; } } return FALSE;//нужно что бы вызвать функцию для прорисовки окда //return TRUE;//не будет вызыватся функция протисовки окна } |
файл bd.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#ifndef BD_H #define BD_H #include <string> using std::string; #include <vector> using std::vector; //функция проверяет данные bool CheckData(string buf); class bd { public: //добавляет строку в БД void AddData(string buf); //получить все елементы из БД vector<string> GetAllElementBd(); //дать имя получить номер string GetNumber(string name); //удалить строку void DeleteStr(string name); //делает поиск строк по имени vector<string> SearchStr(string buf); }; #endif |
файл bd.cpp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 |
#include <string> using std::string; #include <fstream> using std::ofstream; using std::ifstream; #include <iostream> using std::endl; #include <Windows.h> #include <regex> using std::regex; using std::regex_search; using std::regex_replace; using std::smatch; #include <cstdlib> using std::exit; #include "bd.h" //функция проверяет данные bool CheckData(string buf) { string s1,s2; smatch sm; if(regex_search(buf,sm,regex("^\\w+;\\d+$"))) return true; else return false; } //добавляет строку в БД void bd::AddData(string buf) { ofstream ofs("data.txt",ofstream::app); if(!ofs) { MessageBox(NULL,(LPCTSTR)"don't open file: data.txt", "AddData",MB_OK|MB_ICONINFORMATION); } else ofs <<buf<<endl; ofs.close(); } //получить все елементы из БД vector<string> bd::GetAllElementBd() { vector<string> v; ifstream ifs("data.txt",ifstream::in); if(ifs) { string s; while(getline(ifs,s)) { s=regex_replace(s,regex("(\\w+);\\d+"),string("$1")); v.push_back(s); } ifs.close(); } return v; } //дать имя получить номер string bd::GetNumber(string name) { ifstream ifs("data.txt",ifstream::in); if(ifs) { string s,s1,s2; while(getline(ifs,s)) { s1=regex_replace(s,regex("(\\w+);\\d+"),string("$1")); if(s1==name) { s2=regex_replace(s,regex("\\w+;(\\d+)"),string("$1")); ifs.close(); return s2; } } return "not found"; } else { MessageBox(NULL,(LPCTSTR)"don't open file: data.txt", "GetNumber",MB_OK|MB_ICONINFORMATION); return "not found"; } } //удалить строку void bd::DeleteStr(string name) { //1.записываем в вектор v данные из data.txt vector<string> v; ifstream ifs("data.txt",ifstream::in); if(ifs) { string s,s1; while(getline(ifs,s)) { s1=regex_replace(s,regex("(\\w+);\\d+"),string("$1")); if(s1==name) continue; v.push_back(s); } } else { MessageBox(NULL,(LPCTSTR)"don't open file: data.txt", "DeleteStr",MB_OK|MB_ICONINFORMATION); } ifs.close(); //Нужно переписать файл data.txt ofstream ofs("data.txt",ofstream::out);//создание нового, пустого файла data.txt if(ofs) { for(int i=0;i<v.size();i++) ofs <<v[i]<<endl; } else { MessageBox(NULL,(LPCTSTR)"don't open file: data.txt and и все ваши данные удалились извините", "DeleteStr",MB_OK|MB_ICONINFORMATION); } ofs.close(); } //делает поиск строк по имени vector<string> bd::SearchStr(string buf) { vector<string> v; ifstream ifs("data.txt",ifstream::in); if(ifs) { smatch sm; string s; while(getline(ifs,s)) { if(regex_search(s,sm,regex("^"+buf, std::regex_constants::icase))) v.push_back(regex_replace(s,regex("(\\w+);\\d+"),string("$1"))); } } else { MessageBox(NULL,(LPCTSTR)"don't open file: data.txt", "SearchStr",MB_OK|MB_ICONINFORMATION); } return v; } |
Ну и нарисовать вы должны прогу такую как на рисунке выше, такой самый рисунок с двумя текстовыми полями и списком и пятью кнопками.
Так щас я обозначу какие у них идентификаторы должны быть по кнопкам
show query result -IDC_SHOW_QUERY
show all list-IDC_SHOW_ALL
add-IDC_ADD
delete-IDC_DELETE
exit-IDC_EXIT
Так ну и пожалуй это все. Базу данных телефонных номеров примерно так создается. Ладно ребятки будем изучать дальше другие графические элементы управления, да в виндовс их уж очень много, пока я только с тремя ознакомился: списки, текстовое поле, статический текст и кнопки. Все дальше рассматриваем другие элементы.
Скачать саму программу telBD.