问个键盘控制和文件操作的问题
题目要求:从文件读一行文本,当按下DEL键时,从行首删除一个字符,当按下Backspace键时,从行尾删除一个字符。我的设想是按下按键时,直接删除文件中的字符。以下是我写的代码,为什么只有一个键能起作用,且删除行尾字符,必须按两次才行;case VK_DELETE和 case VK_BACK谁放上面,就能实现哪个键的操作,盼指点下。
#include<afx.h>
#include <windows.h>
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<string>
using namespace std; int WINAPI WinMain(HINSTANCE,HINSTANCE,LPSTR,int);
LRESULT CALLBACK WndProc( HWND,UINT, WPARAM,LPARAM);
void erasefirst();
void eraseend(); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon= LoadIcon(NULL, (LPCTSTR)IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = "SeeKeyMessage";
wcex.hIconSm = LoadIcon(NULL,(LPCTSTR)IDI_APPLICATION);
if(!RegisterClassEx(&wcex))//
return FALSE;
int SW_XFS = GetSystemMetrics(SM_CXSCREEN);//获取屏幕横向的像素尺寸
int SW_YFS = GetSystemMetrics(SM_CYSCREEN);
HWND hWnd;
hWnd = CreateWindowEx(WS_EX_CLIENTEDGE,
"SeeKeyMessage",
"键盘控制输出",
WS_OVERLAPPEDWINDOW,
100, 200, 800, 300,
NULL,
NULL,
hInstance,
NULL);
if(!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
if(!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
} LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hDC;
PAINTSTRUCT ps;
int i;
char buffer[40];
CStdioFile cf("test.txt",CFile::modeRead);
cf.ReadString(buffer,40);
cf.Close();
switch(message)
{
case WM_KEYDOWN:
switch(wParam)
case VK_BACK:
eraseend(); //调用删除最后一个字符函数
break;
case VK_DELETE:
erasefirst();//调用删除第一个字符函数
break;
case WM_KEYUP:
InvalidateRect(hWnd,NULL,TRUE);
break;
case WM_PAINT:
hDC = BeginPaint(hWnd,&ps);
for(i=0;i<strlen(buffer)/2;i++)
{
TextOut(hDC,20+30*i,20,&buffer[2*i],2);
}
EndPaint(hWnd,&ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}
void erasefirst()//删除第一个字符函数
{
string s;
ifstream in("test.txt");
if(getline(in,s))
s.erase(0,2);
in.close();
DeleteFile("test.txt");
ofstream out("test.txt");
out<<s;
out.close();
}
void eraseend()//删除文件最后一个字符函数
{
string s;
ifstream in("test.txt");
if(getline(in,s))
s.erase(s.end()-1);
in.close();
DeleteFile("test.txt");
ofstream out("test.txt");
out<<s;
out.close();
}