在程序调试的很多情况下,我更愿意把一些运行信息发送到记事本显示。和写log相比,这更直接;和TRACE相比,TRACE一般在F5-DEBUG跟踪运行时才起作用。
还是用代码说话吧:
//启动一个应用程序(记事本)
//dwFlag= CREATE_NEW_CONSOLE 影响结果,这样和用户手动启动进程更一致
bool RunApp(LPCTSTR app_path, LPTSTR doc_open=0, DWORD dwFlag=0)
{
assert(app_path);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if(!CreateProcess( app_path, // Application name
doc_open, // Application arguments
0, // Process handle not inheritable
0, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
dwFlag, // Creation flags
0, // Use parent's environment block
0, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
){
TRACE(_T("CreateProcess %s failed, error= %d.\n"), app_path, GetLastError());
return false;
}
return true;
}
//
HWND GetAppWnd(LPCTSTR appName)//=_T("Notepad")
{
assert(appName);
static HWND hNotepad(0);
if(hNotepad){
if(!IsWindow(hNotepad))//maybe closed!
hNotepad= 0;
}
if(hNotepad==0){
hNotepad= ::FindWindow(appName, 0);
static int runoted(0);
if(hNotepad==0 && !runoted){
runoted= 1;
//MessageBox in worker-thread works dead!
// MessageBoxD(_T("run Notepad.exe, please!"));
TCHAR buf[64];
GetWindowsDirectory(buf, 100);
lstrcat(buf, _T("\\"));
lstrcat(buf, appName);
lstrcat(buf, _T(".exe"));
if(RunApp(buf, 0))
hNotepad= ::FindWindow(appName, 0);
}
}
return hNotepad;
}
bool SendTextToEdit(LPCTSTR text, HWND hEdit)
{
//下面这种实现可行并且用了一段时间(基于WM_GETTEXT,WM_SETTEXT)
const int bufsize= 4096;
TCHAR szBuf[bufsize]= {0};
int len= lstrlen(text);
int oldlen = (int)::SendMessage(hEdit, WM_GETTEXTLENGTH, 0, 0);
if(oldlen+len+4 > bufsize){
TRACE(_T("remove some text from Notepad.exe, please!\n"));
return false;
}
::SendMessage(hEdit, WM_GETTEXT, oldlen+1, (LPARAM)szBuf);
TCHAR* pBuf= szBuf+oldlen;
memcpy(pBuf, text, sizeof(TCHAR)*len);
if(pBuf[len-2]!=_T('\r') || pBuf[len-1]!=_T('\n')){
pBuf[len++]= _T('\r');
pBuf[len++]= _T('\n');
}
pBuf[len] = 0;
::SendMessage(hEdit, WM_SETTEXT, 0, (LPARAM)szBuf);
return true;
}
//SendTextToNotepad: 把测试信息发到记事本显示
//注意:内部会自动处理换行;text最好不要带换行符(如果带的话就用"\r\n")
//MFC-TRACE能处理好"\r\n"的所有情形(都是换行): "\r","\n","\n\r","\r\n"
bool SendTextToNotepad(LPCTSTR text)
{
bool sucd= false;
for(int t=0; t<1; ++t){
/* if(chkUserForSendText){
static int isme(-1);
if(isme==-1)
isme= IsMyTest(0);
if(isme!=1)
break;
}*/
static HWND hEdit(0);
if(hEdit==0){
HWND hNotepad= GetAppWnd(_T("Notepad"));
if(hNotepad==NULL)
break;
hEdit = FindWindowEx(hNotepad, 0, _T("Edit"), 0);
if(hEdit == 0 )
break;
}
sucd= SendTextToEdit(text, hEdit);
}
if(!sucd){
if(lstrlen(text)<256)
TRACE(_T("SendText failed: %s\n"), text);
else
TRACE(_T("SendText failed!\n"));
}
return sucd;
}