Tutoriais e Programação
Linguagem C - Projeto Espião IV
- Detalhes
-
Categoria: Linguagem C
-
Atualização: Domingo, 30 Novembro 2008 22:37
-
Autor: vovó Vicki
-
Acessos: 10697
Neste tutorial você encontra o código fonte completo do Projeto Espião. Este inclui o código gerado automaticamente pelo Wedit e o código apresentado e explicado nos tutoriais anteriores. É importante para se ter uma visão geral do projeto.
/*<---------------------------------------------------------------------->*/
#include
#include
#include
#include
#include
#include "espiaores.h"
#define IDJANELATREE 10545
/*<---------------------------------------------------------------------->*/
HINSTANCE hInst; // manipulador da instância
HWND hwndMain; // manipulador da janela principal
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
static HWND _stdcall janelaTree(HWND hWnd,int ID);
int criaTree(HWND parent);
void Scan(HWND hTree,HTREEITEM hNoPai,HWND Inicio);
LRESULT TrataWmNotify(HWND hwnd, WPARAM wParam, LPARAM lParam);
static HWND PegaItemInfo(HWND hwndTree,HTREEITEM hti);
void PoeTextoStatus(HWND hParent,HWND hwnd);
static char * NomeIDProcesso( DWORD processoID );
// Variáveis globais para o controle da barra de status.
HWND hWndStatusbar;
/*------------------------------------------------------------------------
Procedure: UpdateStatusBar ID:1
Purpose: Updates the statusbar control with the appropiate text
Input: lpszStatusString: Charactar string that will be shown
partNumber: index of the status bar part number.
displayFlags: Decoration flags
Output: none
Errors: none
------------------------------------------------------------------------*/
void UpdateStatusBar(
LPSTR lpszStatusString, WORD partNumber, WORD displayFlags)
{
SendMessage(hWndStatusbar,
SB_SETTEXT,
partNumber | displayFlags,
(LPARAM)lpszStatusString);
}
/*------------------------------------------------------------------------
Procedure: MsgMenuSelect ID:1
Purpose: Shows in the status bar a descriptive explanation of
the purpose of each menu item.The message
WM_MENUSELECT is sent when the user starts browsing
the menu for each menu item where the mouse passes.
Input: Standard windows.
Output: The string from the resources string table is shown
Errors: If the string is not found nothing will be shown.
------------------------------------------------------------------------*/
LRESULT MsgMenuSelect(HWND hwnd, UINT uMessage, WPARAM wparam, LPARAM lparam)
{
static char szBuffer[256];
UINT nStringID = 0;
UINT fuFlags = GET_WM_MENUSELECT_FLAGS(wparam, lparam) & 0xffff;
UINT uCmd = GET_WM_MENUSELECT_CMD(wparam, lparam);
HMENU hMenu = GET_WM_MENUSELECT_HMENU(wparam, lparam);
szBuffer[0] = 0; // First reset the buffer
if (fuFlags == 0xffff && hMenu == NULL) // Menu has been closed
nStringID = 0;
else if (fuFlags & MFT_SEPARATOR) // Ignore separators
nStringID = 0;
else if (fuFlags & MF_POPUP) // Popup menu
{
if (fuFlags & MF_SYSMENU) // System menu
nStringID = IDS_SYSMENU;
else
// Get string ID for popup menu from idPopup array.
nStringID = 0;
} // for MF_POPUP
else // Must be a command item
nStringID = uCmd; // String ID == Command ID
// Load the string if we have an ID
if (0 != nStringID)
LoadString(hInst, nStringID, szBuffer, sizeof(szBuffer));
// Finally... send the string to the status bar
UpdateStatusBar(szBuffer, 0, 0);
return 0;
}
/*------------------------------------------------------------------------
Procedure: InitializeStatusBar ID:1
Purpose: Initialize the status bar
Input: hwndParent: the parent window
nrOfParts: The status bar can contain more than one
part. What is difficult, is to figure out how this
should be drawn. So, for the time being only one is
being used...
Output: The status bar is created
Errors:
------------------------------------------------------------------------*/
void InitializeStatusBar(HWND hwndParent,int nrOfParts)
{
const int cSpaceInBetween = 8;
int ptArray[40]; // Array defining the number of parts/sections
RECT rect;
HDC hDC;
/* * Fill in the ptArray... */
hDC = GetDC(hwndParent);
GetClientRect(hwndParent, &rect);
ptArray[nrOfParts-1] = rect.right;
//---TODO--- Add code to calculate the size of each part of the status
// bar here.
ReleaseDC(hwndParent, hDC);
SendMessage(hWndStatusbar,
SB_SETPARTS,
nrOfParts,
(LPARAM)(LPINT)ptArray);
UpdateStatusBar("Ready", 0, 0);
//---TODO--- Add code to update all fields of the status bar here.
// As an example, look at the calls commented out below.
// UpdateStatusBar("Cursor Pos:", 1, SBT_POPOUT);
// UpdateStatusBar("Time:", 3, SBT_POPOUT);
}
/*------------------------------------------------------------------------
Procedure: CreateSBar ID:1
Purpose: Calls CreateStatusWindow to create the status bar
Input: hwndParent: the parent window
initial text: the initial contents of the status bar
Output:
Errors:
------------------------------------------------------------------------*/
static BOOL CreateSBar(HWND hwndParent,char *initialText,int nrOfParts)
{
hWndStatusbar = CreateStatusWindow(WS_CHILD | WS_VISIBLE |
WS_BORDER|SBARS_SIZEGRIP,
initialText,
hwndParent,
IDM_STATUSBAR);
if(hWndStatusbar)
{
InitializeStatusBar(hwndParent,nrOfParts);
return TRUE;
}
return FALSE;
}
/*<---------------------------------------------------------------------->*/
/* 0-> */
static BOOL InitApplication(void)
{
WNDCLASS wc;
memset(&wc,0,sizeof(WNDCLASS));
wc.style = CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ;
wc.lpfnWndProc = (WNDPROC)MainWndProc;
wc.hInstance = hInst;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszClassName = "espiaoWndClass";
wc.lpszMenuName = MAKEINTRESOURCE(IDMAINMENU);
wc.hCursor = LoadCursor(NULL,IDC_ARROW);
wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
if (!RegisterClass(&wc))
return 0;
/* 0<- */
// ---TODO--- Call module specific initialization routines here
return 1;
}
/*<---------------------------------------------------------------------->*/
/* 1-> */
HWND CreateespiaoWndClassWnd(void)
{
return CreateWindow("espiaoWndClass","espiao",
WS_MINIMIZEBOX|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|
WS_MAXIMIZEBOX|WS_CAPTION|WS_BORDER|WS_SYSMENU|WS_THICKFRAME,
CW_USEDEFAULT,0,CW_USEDEFAULT,0,
NULL,
NULL,
hInst,
NULL);
}
/* 1<- */
/*<---------------------------------------------------------------------->*/
void MainWndProc_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch(id) {
case IDM_NEW:
criaTree(hwnd);
break;
case IDM_EXIT:
PostMessage(hwnd,WM_CLOSE,0,0);
break;
}
}
/*<---------------------------------------------------------------------->*/
/* 2-> */
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
static HWND hwndTree;
RECT rc, rcStatus;
switch (msg) {
/* 3-> */
case WM_CREATE:
hwndTree = janelaTree(hwnd,IDJANELATREE);
break;
case WM_NOTIFY:
return TrataWmNotify(hwnd,wParam,lParam);
case WM_SIZE:
SendMessage(hWndStatusbar,msg,wParam,lParam);
InitializeStatusBar(hWndStatusbar,1);
GetClientRect(hwnd,&rc);
GetWindowRect(hwndTree,&rcStatus);
rc.bottom -= rcStatus.bottom - rcStatus.top;
MoveWindow(hwndTree,0,0,rc.right,rc.bottom,1);
break;
case WM_MENUSELECT:
return MsgMenuSelect(hwnd,msg,wParam,lParam);
case WM_COMMAND:
HANDLE_WM_COMMAND(hwnd,wParam,lParam,MainWndProc_OnCommand);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,msg,wParam,lParam);
}
/* 3<- */
return 0;
}
/* 2<- */
/*<---------------------------------------------------------------------->*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, INT nCmdShow)
{
MSG msg;
HANDLE hAccelTable;
hInst = hInstance;
if (!InitApplication())
return 0;
hAccelTable = LoadAccelerators(hInst,MAKEINTRESOURCE(IDACCEL));
if ((hwndMain = CreateespiaoWndClassWnd()) == (HWND)0)
return 0;
CreateSBar(hwndMain,"Ready",1);
ShowWindow(hwndMain,SW_SHOW);
while (GetMessage(&msg,NULL,0,0)) {
if (!TranslateAccelerator(msg.hwnd,hAccelTable,&msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
/*<----------------------------------------------------------------------
NOSSAS FUNÇÕES
--------------------------------------------------------------------------->*/
static HWND _stdcall janelaTree(HWND hWnd,int ID)
{
return CreateWindowEx(WS_EX_CLIENTEDGE,WC_TREEVIEW,"",
WS_VISIBLE|WS_CHILD|WS_BORDER|TVS_HASLINES|
TVS_HASBUTTONS|TVS_DISABLEDRAGDROP,
0,0,0,0,
hWnd,(HMENU)ID,hInst,NULL);
}
/*<---------------------------------------------------------------------->*/
int criaTree(HWND mae)
{
HWND Inicio = GetDesktopWindow();
HWND hTree = GetDlgItem(mae,IDJANELATREE);
TV_INSERTSTRUCT itemTree;
HTREEITEM hNovoNo;
SendMessage(hTree,WM_SETREDRAW,0,0);
TreeView_DeleteAllItems(hTree);
memset(&itemTree,0,sizeof(itemTree));
itemTree.hParent = TVI_ROOT;
itemTree.hInsertAfter = TVI_LAST;
itemTree.item.mask = TVIF_TEXT | TVIF_PARAM;
itemTree.item.pszText = "Desktop";
hNovoNo = TreeView_InsertItem(hTree,&itemTree);
Inicio = GetWindow(Inicio,GW_CHILD);
Scan(hTree,hNovoNo,Inicio);
TreeView_Expand(hTree,hNovoNo,TVE_EXPAND);
SendMessage(hTree,WM_SETREDRAW,1,0);
return 1;
}
/*<---------------------------------------------------------------------->*/
void Scan(HWND hTree,HTREEITEM hNoPai,HWND Inicio)
{
HWND hwnd = Inicio, hwnd1;
TV_INSERTSTRUCT novoItemTree;
HTREEITEM htiNovoNo;
char bufTxt[256],NomeClasseBuf[256],Saida[1024];
while (hwnd != NULL) {
SendMessage(hwnd,WM_GETTEXT,250,(LPARAM) bufTxt);
GetClassName(hwnd,NomeClasseBuf,250);
wsprintf(Saida,"\"%s\" %s",bufTxt,NomeClasseBuf);
memset(&novoItemTree,0,sizeof(novoItemTree));
novoItemTree.hParent = hNoPai;
novoItemTree.hInsertAfter = TVI_LAST;
novoItemTree.item.mask = TVIF_TEXT | TVIF_PARAM;
novoItemTree.item.pszText = (LPSTR) Saida;
novoItemTree.item.lParam = (LPARAM) hwnd;
htiNovoNo = TreeView_InsertItem(hTree,&novoItemTree);
if((hwnd1=GetWindow(hwnd,GW_CHILD))!=NULL)
Scan(hTree,htiNovoNo,hwnd1);
hwnd=GetWindow(hwnd,GW_HWNDNEXT);
}
}
/*<---------------------------------------------------------------------->*/
LRESULT TrataWmNotify(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
NMHDR *apontaGrito;
TV_HITTESTINFO testaClique;
HWND hTree = GetDlgItem(hwnd,IDJANELATREE);
HTREEITEM hti;
HWND hwndAlvo;
apontaGrito = (NMHDR *)lParam;
switch (apontaGrito->code) {
case NM_CLICK:
memset(&testaClique,0,sizeof(TV_HITTESTINFO));
GetCursorPos(&testaClique.pt);
MapWindowPoints(HWND_DESKTOP,hTree,&testaClique.pt,1);
hti = TreeView_HitTest(hTree,&testaClique);
if (hti == (HTREEITEM)0) break;
hwndAlvo = PegaItemInfo(hTree,hti);
PoeTextoStatus(hwnd,hwndAlvo);
break;
}
return DefWindowProc(hwnd,WM_NOTIFY,wParam,lParam);
}
/*<---------------------------------------------------------------------->*/
static HWND PegaItemInfo(HWND hwndTree,HTREEITEM hti)
{
TV_ITEM tvi;
memset(&tvi,0,sizeof(TV_ITEM));
tvi.mask = TVIF_PARAM;
tvi.hItem = hti;
TreeView_GetItem(hwndTree,&tvi);
return (HWND) tvi.lParam;
}
/*<---------------------------------------------------------------------->*/
void PoeTextoStatus(HWND hParent,HWND hwnd)
{
RECT rc;
HANDLE pid;
char info[4096],*pNomeProcesso;
GetWindowRect(hwnd,&rc);
GetWindowThreadProcessId(hwnd,&pid);
pNomeProcesso = NomeIDProcesso((ULONG)pid);
wsprintf(info,
"Handle: 0x%x %s, esq %d, topo %d, dir %d, base %d,
altura %d, larg %d, Processo: %s",
hwnd,
IsWindowVisible(hwnd)? "Visível" : "Escondida",
rc.left,rc.top,rc.right,rc.bottom,
rc.bottom-rc.top,
rc.right-rc.left,
pNomeProcesso);
UpdateStatusBar(info, 0, 0);
}
/*<---------------------------------------------------------------------->*/
static char * NomeIDProcesso( DWORD processoID )
{
static char szNomeProcesso[MAX_PATH];
HMODULE hMod;
DWORD cbNeeded;
HANDLE hProcesso = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ, FALSE, processoID );
szNomeProcesso[0] = 0;
if ( hProcesso ) {
if ( EnumProcessModules( hProcesso, &hMod, sizeof(hMod),
&cbNeeded) ) {
GetModuleBaseName( hProcesso, hMod, szNomeProcesso,
sizeof(szNomeProcesso) );
}
CloseHandle( hProcesso );
}
return szNomeProcesso;
}
O código precisa ser compilado com a biblioteca psapi.lib
Observações da vó
Agradeço a paciência e o interesse pelo tutorial. Caso tenha alguma dúvida, crítica, correção ou sugestão, entre em contato.
Todos os exemplos destes tutoriais foram extraídos do tutorial de C do autor do lcc-win32, Jacob Navia, a quem só tenho que agradecer por disponibilizar gratuitamente esta plataforma de desenvolvimento na Internet. Não conheço o autor do software e nem estou ligada ao desenvolvimento desta plataforma, apenas a utilizo e, por sua excelência, achei justo divulgar o trabalho do Navia.
Os textos são de minha autoria, baseados em informações técnicas, artigos, alguns livros e na minha experiência pessoal. Espero que tenham agradado.
Grande abraço
vó Vicki
Вадим Логофет банкирчугунный казан с крышкой сковородойwobsблюда приготовленныелобановский классглавное новостилобановский александр