// Function to receive messages from the server
void ReceiveMessages(SOCKET sock) {
char buffer[1024];
while (true) {
ZeroMemory(buffer, sizeof(buffer));
int bytesReceived = recv(sock, buffer, sizeof(buffer), 0);
code
if (bytesReceived > 0) {
buffer[bytesReceived] = '\0'; // Null-terminate the received message
UpdateChatWindow("Server: " + std::string(buffer));
} else if (bytesReceived == 0) {
UpdateChatWindow("Server closed the connection.");
break;
} else {
UpdateChatWindow("Error receiving data.");
break;
}
}
}
// Function to update the chat area
void UpdateChatWindow(const std::string& message) {
chatMutex.lock();
SendMessage(hChatArea, EM_SETSEL, -1, -1); // Move cursor to end
SendMessage(hChatArea, EM_REPLACESEL, TRUE, (LPARAM)message.c_str());
SendMessage(hChatArea, EM_REPLACESEL, TRUE, (LPARAM)"\r\n");
chatMutex.unlock();
}
make this chat app client side more beautiful
Enhancing the visual appeal of your chat client involves improving the layout, using better fonts and colors, adding user-friendly features, and ensuring a responsive design. Below is an improved version of your chat client with these enhancements:
Custom Fonts and Colors: Use a more modern font and set distinct colors for different UI elements.
Improved Layout: Organize controls with consistent margins and alignments.
Resizable Window Support: Allow the window to be resized, and adjust the controls accordingly.
Enhanced Controls: Use a RichEdit control for richer text formatting and better appearance.
Send on Enter: Allow users to send messages by pressing the Enter key.
Status Bar: Add a status bar to display connection status and other information.
Here's the updated code with these improvements:
cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <winsock2.h>
#include <windows.h>
#include <commctrl.h>
#include <thread>
#include <string>
#include <mutex>
#include <richedit.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "comctl32.lib")
// Function prototypes
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void ReceiveMessages(SOCKET sock);
void UpdateChatWindow(const std::string& message);
void SetCustomFont(HWND hwnd, int pointSize);
// Global variables
HWND hChatArea;
HWND hInputField;
HWND hSendButton;
HWND hStatusBar;
SOCKET clientSocket;
std::mutex chatMutex;
HFONT hFont;
// Constants for control IDs
#define IDC_SEND_BUTTON 1
#define IDC_STATUS_BAR 2
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// Initialize common controls (for status bar)
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_BAR_CLASSES;
InitCommonControlsEx(&icex);
// Initialize Winsock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
MessageBox(NULL, "Winsock initialization failed.", "Error", MB_OK | MB_ICONERROR);
return -1;
}
// Create a socket
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == INVALID_SOCKET) {
MessageBox(NULL, "Failed to create socket.", "Error", MB_OK | MB_ICONERROR);
WSACleanup();
return -1;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(54000);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
// Connect to server
if (connect(clientSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
MessageBox(NULL, "Failed to connect to server.", "Error", MB_OK | MB_ICONERROR);
closesocket(clientSocket);
WSACleanup();
return -1;
}
// Create main window
const char CLASS_NAME[] = "ChatClient";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = CreateSolidBrush(RGB(240, 240, 240)); // Light grey background
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
"Chat Client",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, 500, 400,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd == NULL) {
MessageBox(NULL, "Failed to create main window.", "Error", MB_OK | MB_ICONERROR);
closesocket(clientSocket);
WSACleanup();
return -1;
}
// Start a thread to handle incoming messages
std::thread receiveThread(ReceiveMessages, clientSocket);
receiveThread.detach();
// Message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
closesocket(clientSocket);
WSACleanup();
return 0;
}
// Window Procedure
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
static HINSTANCE hInst;
switch (uMsg) {
case WM_CREATE: {
hInst = GetModuleHandle(NULL);
// Create custom font
LOGFONT lf = { 0 };
lf.lfHeight = 16;
lf.lfWeight = FW_NORMAL;
strcpy_s(lf.lfFaceName, "Segoe UI");
hFont = CreateFontIndirect(&lf);
// Create chat area (Rich Edit Control)
hChatArea = CreateWindowEx(
WS_EX_CLIENTEDGE, "RichEdit20A", "",
WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL,
10, 10, 460, 280, hwnd, NULL, hInst, NULL
);
// Set font for chat area
SendMessage(hChatArea, WM_SETFONT, (WPARAM)hFont, TRUE);
// Initialize Rich Edit control
SendMessage(hChatArea, EM_SETBKGNDCOLOR, 0, (LPARAM)RGB(255, 255, 255));
// Create input field
hInputField = CreateWindowEx(
WS_EX_CLIENTEDGE, "Edit", "",
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL,
10, 300, 360, 30, hwnd, NULL, hInst, NULL
);
SendMessage(hInputField, WM_SETFONT, (WPARAM)hFont, TRUE);
// Create send button
hSendButton = CreateWindow(
"BUTTON", "Send",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
380, 300, 90, 30,
hwnd, (HMENU)IDC_SEND_BUTTON, hInst, NULL
);
SendMessage(hSendButton, WM_SETFONT, (WPARAM)hFont, TRUE);
// Create status bar
hStatusBar = CreateWindowEx(
0, STATUSCLASSNAME, NULL,
WS_CHILD | WS_VISIBLE | SBARS_SIZEGRIP,
0, 0, 0, 0,
hwnd, (HMENU)IDC_STATUS_BAR, hInst, NULL
);
// Set initial text in status bar
SendMessage(hStatusBar, SB_SETTEXT, 0, (LPARAM)"Connected to server.");
// Enable send on Enter key
SendMessage(hInputField, EM_SETLIMITTEXT, 512, 0);
} break;
case WM_SIZE: {
// Adjust controls when window is resized
int width = LOWORD(lParam);
int height = HIWORD(lParam);
// Resize chat area
MoveWindow(hChatArea, 10, 10, width - 20, height - 80, TRUE);
// Resize input field
MoveWindow(hInputField, 10, height - 60, width - 110, 30, TRUE);
// Move send button
MoveWindow(hSendButton, width - 90, height - 60, 80, 30, TRUE);
// Resize status bar
SendMessage(hStatusBar, WM_SIZE, 0, 0);
} break;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_SEND_BUTTON) { // Send button clicked
char buffer[512];
GetWindowText(hInputField, buffer, sizeof(buffer));
std::string msgStr(buffer);
// Trim whitespace
msgStr.erase(0, msgStr.find_first_not_of(" \n\r\t"));
msgStr.erase(msgStr.find_last_not_of(" \n\r\t") + 1);
if (!msgStr.empty()) {
int sendResult = send(clientSocket, msgStr.c_str(), msgStr.length(), 0);
if (sendResult != SOCKET_ERROR) {
UpdateChatWindow("You: " + msgStr);
SetWindowText(hInputField, ""); // Clear input field
} else {
UpdateChatWindow("Failed to send message.");
}
}
}
break;
case WM_CHAR:
if (wParam == VK_RETURN && GetFocus() == hInputField) {
// Prevent ding sound
return 0;
}
break;
case WM_KEYDOWN:
if (wParam == VK_RETURN && GetFocus() == hInputField) {
// Trigger send button
SendMessage(hwnd, WM_COMMAND, MAKEWPARAM(IDC_SEND_BUTTON, 0), 0);
return 0;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
// Function to receive messages from the server
void ReceiveMessages(SOCKET sock) {
char buffer[512];
while (true) {
ZeroMemory(buffer, sizeof(buffer));
int bytesReceived = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived > 0) {
buffer[bytesReceived] = '\0'; // Null-terminate the received message
UpdateChatWindow("Server: " + std::string(buffer));
}
else if (bytesReceived == 0) {
UpdateChatWindow("Server closed the connection.");
break;
}
else {
UpdateChatWindow("Error receiving data.");
break;
}
}
// Optionally, update status bar or disable input field
}
// Function to update the chat area
void UpdateChatWindow(const std::string& message) {
std::lock_guard<std::mutex> lock(chatMutex);
// Format message with timestamp
SYSTEMTIME st;
GetLocalTime(&st);
char timeBuffer[100];
sprintf_s(timeBuffer, "[%02d:%02d:%02d] %s\r\n",
st.wHour, st.wMinute, st.wSecond, message.c_str());
// Append message to chat area
SendMessage(hChatArea, EM_SETSEL, -1, -1); // Move cursor to end
SendMessage(hChatArea, EM_REPLACESEL, FALSE, (LPARAM)timeBuffer);
}
Detailed Enhancements Explained
Custom Fonts and Colors:
Font: The SetCustomFont function (in this case, integrated into WM_CREATE) sets a modern font (Segoe UI, which is widely used in Windows applications) with a size of 16 points for better readability.
Background Color: The main window has a light grey background (RGB(240, 240, 240)) to make it visually pleasant and reduce glare.
Improved Layout:
Resizable Window: The WM_SIZE message handler adjusts the size and position of the chat area, input field, send button, and status bar based on the window's current size, allowing the window to be resized dynamically.
Margins and Alignments: Consistent margins (10 pixels from the left and top) and aligned controls ensure a clean and organized interface.
Enhanced Controls:
Rich Edit Control for Chat Area: Replacing the standard EDIT control with a RichEdit20A control allows for richer text formatting and better appearance.
Send Button with Default Push Behavior: The send button is created with BS_DEFPUSHBUTTON style, making it visually prominent and responsive to keyboard interactions.
Status Bar: A status bar (hStatusBar) provides real-time feedback about the connection status and other relevant information.
User-Friendly Features:
Send on Enter Key: Users can send messages by pressing the Enter key, enhancing usability. The WM_KEYDOWN and WM_CHAR message handlers manage this behavior.
Input Validation: Trimming whitespace from the input ensures that accidental spaces or blank messages are not sent.
Message Timestamps: Each message is prefixed with a timestamp ([HH:MM:SS]) to keep track of conversation history.
Thread Safety:
Mutex Locking: The std::mutex chatMutex ensures that updates to the chat area are thread-safe, preventing race conditions when multiple threads attempt to write to the UI simultaneously.
Error Handling:
Additional Recommendations
Rich Text Formatting: Utilize the RichEdit control to differentiate between users' messages and server messages with different colors or styles.
cpp
// Example: Make server messages blue
void UpdateChatWindow(const std::string& message) {
std::lock_guard<std::mutex> lock(chatMutex);
SYSTEMTIME st;
GetLocalTime(&st);
char timeBuffer[100];
sprintf_s(timeBuffer, "[%02d:%02d:%02d] %s\r\n",
st.wHour, st.wMinute, st.wSecond, message.c_str());
// Assume server messages start with "Server:"
COLORREF color = RGB(0, 0, 0); // Default black
if (message.find("Server:") == 0) {
color = RGB(0, 0, 255); // Blue for server
}
else if (message.find("You:") == 0) {
color = RGB(0, 128, 0); // Green for user
}
// Set selection to end
SendMessage(hChatArea, EM_SETSEL, -1, -1);
// Set text color
CHARFORMAT cf;
cf.cbSize = sizeof(cf);
cf.dwMask = CFM_COLOR;
cf.crTextColor = color;
SendMessage(hChatArea, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
// Insert text
SendMessage(hChatArea, EM_REPLACESEL, FALSE, (LPARAM)timeBuffer);
}
Adding an Icon: Incorporate an application icon to make the window look more professional. Add an .ico file to your project and load it using LoadIcon.
cpp
// In WM_CREATE, after setting other window properties
HICON hIcon = (HICON)LoadImage(hInst, "chat_icon.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE);
if (hIcon) {
SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
}
By implementing these enhancements, your chat client will not only look more professional and visually appealing but also provide a better user experience. Feel free to further customize fonts, colors, and layouts to match your specific design preferences.
Connection Errors: Proper error messages are displayed if the client fails to create a socket or connect to the server.
Message Sending Errors: If sending a message fails, the user is notified within the chat area.
Input Field Placeholder: Provide a hint in the input field to guide users.
cpp
// In WM_CREATE, after creating hInputField
SendMessage(hInputField, EM_SETCUEBANNER, 0, (LPARAM)"Type your message here...");
Scrollable Chat Area: Ensure the RichEdit control properly handles scrollbars for lengthy conversations. The current setup with WS_VSCROLL and ES_AUTOVSCROLL already aids in this.
Graceful Shutdown: Handle the clean disconnection from the server when the application closes.
cpp
case WM_CLOSE:
// Notify server about disconnection if necessary
closesocket(clientSocket);
DestroyWindow(hwnd);
break;