首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

Win32有关问题

2012-07-30 
Win32问题[codeC/C++][/// WinMsg.cpp : Defines the entry point for the application.//#include stda

Win32问题
[code=C/C++][/// WinMsg.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "stdio.h"
#include "resource.h"
#include "malloc.h"
#include "memory.h"

HINSTANCE g_hInst = NULL;
HANDLE g_hOutput = NULL;

int g_nXPos = 0;
int g_nYPos = 0;

CHAR g_szText[256] = {0};


void OnChar(HWND hWnd, WPARAM wParam)
{  
  sprintf(g_szText, "WM_CHAR: %c", wParam);
}

void OnSave()
{
CHAR *pszBuff = (CHAR *)malloc( sizeof(g_szText) + 1 );
  memset( pszBuff, 0, sizeof(g_szText) + 1 );
   
memcpy(pszBuff, g_szText, sizeof(g_szText));
  FILE * pFile = fopen( "c:\\my.txt", "w" );
   
  fwrite( pszBuff, 1, sizeof(g_szText), pFile );

  fclose( pFile );
  free( pszBuff );
}

void OnCommand(HWND hWnd, WPARAM wParam, LPARAM lParam)
{
UINT iId = LOWORD(wParam);
switch (iId)
{
case ID_SAVE:
OnSave();
break;
}
}

LRESULT CALLBACK MsgProc(HWND hWnd,
  UINT nMsg,
  WPARAM wParam,
  LPARAM lParam)
{
   
  switch (nMsg)
  {
  case WM_CHAR:
  OnChar(hWnd, wParam);
  break;
  case WM_DESTROY:
  PostQuitMessage(0);
  break;
case WM_COMMAND:
OnCommand(hWnd, wParam, lParam);
break;
  }
  return DefWindowProc(hWnd, nMsg, wParam, lParam);
}

BOOL Register(LPSTR pszClassName)
{
  WNDCLASSEX wce = {0};
  wce.cbSize = sizeof(wce);
  wce.cbClsExtra = 0;
  wce.cbWndExtra = 0;
  wce.hInstance = g_hInst;
  wce.style = CS_HREDRAW|CS_VREDRAW;
  wce.hCursor = NULL;
  wce.hIcon = NULL;
  wce.hIconSm = NULL;
  wce.hbrBackground = (HBRUSH)(COLOR_WINDOW);
  wce.lpfnWndProc = MsgProc;
  wce.lpszClassName = pszClassName;
  wce.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
  ATOM nAtom = RegisterClassEx(&wce);
  if (0==nAtom)
  {
  return FALSE;
  }
  return TRUE;
}

HWND Create(LPSTR pszClassName)
{
  HWND hWnd = CreateWindowEx(0,pszClassName,"Main", WS_OVERLAPPEDWINDOW, 
  CW_USEDEFAULT, CW_USEDEFAULT,
  CW_USEDEFAULT,CW_USEDEFAULT,
  NULL, NULL, g_hInst, NULL);
  return hWnd;
}

void Display(HWND hWnd)
{
  ShowWindow(hWnd, SW_SHOW);
  UpdateWindow(hWnd);
}

void Message()
{
  MSG msg = {0};
  while(GetMessage(&msg, NULL, 0, 0))
  {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
  }
}
int APIENTRY WinMain(HINSTANCE hInstance,
  HINSTANCE hPrevInstance,
  LPSTR lpCmdLine,
  int nCmdShow)
{
  g_hInst = hInstance;

  Register("MSGWND");
  HWND hWnd = Create("MSGWND");
  Display(hWnd);
  Message();
return 0;
}


问题:我运行后按键盘在my.txt中只能保存最后一个按键,其它全是乱码.
如我按了a键和e键后在用Notepad++打开my.txt文件显示如下:
WM_CHAR: e其它全是黑底白字的NUL





]

[解决办法]
++
OnChar改进了一下
void OnChar(HWND hWnd, WPARAM wParam)


{
char BUF[]="WM_CHAR:0\n";
BUF[8]=(CHAR)wParam;
strcat(g_szText,BUF);
}

探讨

FILE * pFile = fopen( "c:\\my.txt", "a+" );

热点排行