使用这样的函数: 
    BOOL CheckMessageQueue() 
    { 
     MSG msg; 
     
     
while (PeekMessage( & msg, NULL,  0 0 , PM_REMOVE)){ 
     
if (msg.message == WM_QUIT) 
     
return  FALSE; 
     TranslateMessage(
& msg); 
     DispatchMessage(
& msg); 
     } 
     
return  TRUE; 
    } 
    
该函数可以实现DoEvents的效果。但有一点不同,如果该函数返回FALSE,说明用户按下了关闭按钮。

posted @ 2006-07-15 01:05 紫雨轩 C++ 阅读(2537) | 评论 (0)编辑 收藏

利用一个函数VirtualQuery可以获取指定内存所在的模块:

inline HMODULE GetModuleFromAddr(PVOID p)

    MEMORY_BASIC_INFORMATION m 
= { 0 };
    VirtualQuery(p, 
&m, sizeof(MEMORY_BASIC_INFORMATION));
    
return (HMODULE) m.AllocationBase;
}

有了上面的函数,就非常容易获取当前模块的句柄(比如在静态LIB链接到DLL的项目中,需要知道模块句柄的情况):

HMODULE hThisModule = GetModuleFromAddr(当前模块中的任意函数或变量地址);

更进一步的应用,假如我们需要知道那个模块在调用自己,可以结合_ReturnAddress() intrinsic来实现:

全局声明:EXTERN_C PVOID _ReturnAddress();

调用:HMODULE hCallerModule = GetModuleFromAddr(_ReturnAddress());


posted @ 2006-07-15 01:04 紫雨轩 C++ 阅读(547) | 评论 (0)编辑 收藏

DWORD Bind(HANDLE hProcess, PCTSTR ptzPath)

    DWORD dwResult 
=   0 ;
    PVOID pvRemote 
=  NULL;
    HANDLE hThread 
=  NULL;
    
do
    { 
        
if  (hProcess  ==  NULL)
        { 
            dwResult 
=   1 ;
            
break ;
        }

        DWORD dwSize 
= (lstrlen(ptzPath)  +   1 *   sizeof (TCHAR);
        pvRemote 
=  VirtualAllocEx(hProcess, NULL, dwSize, MEM_COMMIT, PAGE_READWRITE);
        
if  (pvRemote  ==  NULL)
        { 
            dwResult 
=   2 ;
            
break ;
        }

        
if  ( ! WriteProcessMemory(hProcess, pvRemote, ptzPath, dwSize, NULL))
        { 
            dwResult 
=   3 ;
            
break ;
        }

        PTHREAD_START_ROUTINE pfnLoadLibraryW 
=  
            (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle(TEXT(
" Kernel32.dll " )), STR_LoadLibrary);
        
if  (pfnLoadLibraryW  ==  NULL)
        { 
            dwResult 
=   4 ;
            
break ;
        }

        hThread 
=  CreateRemoteThread(hProcess, NULL,  0 , pfnLoadLibraryW, pvRemote,  0 , NULL);
        
if  (hThread  ==  NULL)
        { 
            dwResult 
=   5 ;
            
break ;
        }

        WaitForSingleObject(hThread, INFINITE);
    }
    
while  (FALSE);

    
if  (hThread)
    { 
        CloseHandle(hThread);
    }
    
if  (pvRemote)
    { 
        VirtualFreeEx(hProcess, pvRemote, 
0 , MEM_RELEASE);
    }
    
if  (hProcess)
    { 
        CloseHandle(hProcess);
    }

    
return  dwResult;
}

posted @ 2006-07-15 01:03 紫雨轩 C++ 阅读(615) | 评论 (0)编辑 收藏

#include  " stdafx.h "
#include 
" Injection.h "
#ifdef _DEBUG
#define  new DEBUG_NEW
#endif


//  唯一的应用程序对象

CWinApp theApp;

using   namespace  std;

typedef 
struct  _RemotePara{ // 参数结构
    char  pMessageBox[ 12 ];
   DWORD dwMessageBox;
}RemotePara;
// 远程线程
DWORD __stdcall ThreadProc (RemotePara  * lpPara){
   typedef 
int  (__stdcall  * MMessageBoxA)(HWND,LPCTSTR,LPCTSTR,DWORD); // 定义MessageBox函数
   MMessageBoxA myMessageBoxA;
   myMessageBoxA 
= (MMessageBoxA) lpPara -> dwMessageBox ; // 得到函数入口地址
   myMessageBoxA(NULL,lpPara -> pMessageBox ,lpPara -> pMessageBox, 0 ); // call
    return   0 ;
}
void  EnableDebugPriv(); // 提升应用级调试权限

int  _tmain( int  argc, TCHAR *  argv[], TCHAR *  envp[])
{
    
const  DWORD THREADSIZE = 1024 * 4 ;
   DWORD byte_write;
   EnableDebugPriv();
// 提升权限
   HANDLE hWnd  =  ::OpenProcess (PROCESS_ALL_ACCESS,FALSE, 760 );
   
if ( ! hWnd) return   0 ;
   
void   * pRemoteThread  = ::VirtualAllocEx(hWnd, 0 ,THREADSIZE,MEM_COMMIT |  MEM_RESERVE,PAGE_EXECUTE_READWRITE);
   
if ( ! pRemoteThread) return   0 ;
   
if ( ! ::WriteProcessMemory(hWnd,pRemoteThread, & ThreadProc,THREADSIZE, 0 ))
   
return   0 ;

   
// 再付值
   RemotePara myRemotePara;
   ::ZeroMemory(
& myRemotePara, sizeof (RemotePara));
   HINSTANCE hUser32 
=  ::LoadLibrary ( " user32.dll " );
   myRemotePara.dwMessageBox 
= (DWORD) ::GetProcAddress (hUser32 ,  " MessageBoxA " );
   strcat(myRemotePara.pMessageBox,
" hello\0 " );
   
// 写进目标进程
   RemotePara  * pRemotePara  = (RemotePara  * ) ::VirtualAllocEx (hWnd , 0 , sizeof (RemotePara),MEM_COMMIT,PAGE_READWRITE); // 注意申请空间时的页面属性
    if ( ! pRemotePara) return   0 ;
   
if ( ! ::WriteProcessMemory (hWnd ,pRemotePara, & myRemotePara, sizeof  myRemotePara, 0 )) return   0 ;

   
// 启动线程
   HANDLE hThread  =  ::CreateRemoteThread (hWnd , 0 , 0 ,(DWORD (__stdcall  * )( void   * ))pRemoteThread ,pRemotePara, 0 , & byte_write);
   
if ( ! hThread){
      
return   0 ;
   }
    
return   0 ;
}

void  EnableDebugPriv(  void  )
{
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;

if  (  !  OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES 
|  TOKEN_QUERY,  & hToken ) )
return ;
if  (  !  LookupPrivilegeValue( NULL, SE_DEBUG_NAME,  & sedebugnameValue ) ){
CloseHandle( hToken );
return ;
}
tkp.PrivilegeCount 
=   1 ;
tkp.Privileges[
0 ].Luid  =  sedebugnameValue;
tkp.Privileges[
0 ].Attributes  =  SE_PRIVILEGE_ENABLED;
if  (  !  AdjustTokenPrivileges( hToken, FALSE,  & tkp,  sizeof  tkp, NULL, NULL ) )
CloseHandle( hToken );
}

posted @ 2006-07-15 01:02 紫雨轩 C++ 阅读(974) | 评论 (1)编辑 收藏

根据文件句柄,获取文件名
#include <windows.h>
#include 
<stdio.h>
#include 
<tchar.h>
#include 
<string.h>
#include 
<psapi.h>

#define BUFSIZE 512

BOOL GetFileNameFromHandle(HANDLE hFile) 
{
  BOOL bSuccess 
= FALSE;
  TCHAR pszFilename[MAX_PATH
+1];
  HANDLE hFileMap;

  
// Get the file size.
  DWORD dwFileSizeHi = 0;
  DWORD dwFileSizeLo 
= GetFileSize(hFile, &dwFileSizeHi); 

  
if( dwFileSizeLo == 0 && dwFileSizeHi == 0 )
  {
     printf(
"Cannot map a file with a length of zero.\n");
     
return FALSE;
  }

  
// Create a file mapping object.
  hFileMap = CreateFileMapping(hFile, 
                    NULL, 
                    PAGE_READONLY,
                    
0
                    
1,
                    NULL);

  
if (hFileMap) 
  {
    
// Create a file mapping to get the file name.
    void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 001);

    
if (pMem) 
    {
      
if (GetMappedFileName (GetCurrentProcess(), 
                             pMem, 
                             pszFilename,
                             MAX_PATH)) 
      {

        
// Translate path with device name to drive letters.
        TCHAR szTemp[BUFSIZE];
        szTemp[
0= '\0';

        
if (GetLogicalDriveStrings(BUFSIZE-1, szTemp)) 
        {
          TCHAR szName[MAX_PATH];
          TCHAR szDrive[
3= TEXT(" :");
          BOOL bFound 
= FALSE;
          TCHAR
* p = szTemp;

          
do 
          {
            
// Copy the drive letter to the template string
            *szDrive = *p;

            
// Look up each device name
            if (QueryDosDevice(szDrive, szName, BUFSIZE))
            {
              UINT uNameLen 
= _tcslen(szName);

              
if (uNameLen < MAX_PATH) 
              {
                bFound 
= _tcsnicmp(pszFilename, szName, 
                    uNameLen) 
== 0;

                
if (bFound) 
                {
                  
// Reconstruct pszFilename using szTemp
                  
// Replace device path with DOS path
                  TCHAR szTempFile[MAX_PATH];
                  _stprintf(szTempFile,
                            TEXT(
"%s%s"),
                            szDrive,
                            pszFilename
+uNameLen);
                  _tcsncpy(pszFilename, szTempFile, MAX_PATH);
                }
              }
            }

            
// Go to the next NULL character.
            while (*p++);
          } 
while (!bFound && *p); // end of string
        }
      }
      bSuccess 
= TRUE;
      UnmapViewOfFile(pMem);
    } 

    CloseHandle(hFileMap);
  }
  printf(
"File name is %s\n", pszFilename);
  
return(bSuccess);
}

开机自动运行
  其中strPath参数表示要设置为自运行的程序的绝对路径。当设置成功时返回true,否则返回false

BOOL SetAutoRun(CString strPath)//开机自动运行
{
   CString str;
   HKEY hRegKey;
   BOOL bResult;
   str
=_T("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
   
if(RegOpenKey(HKEY_LOCAL_MACHINE, str, &hRegKey) != ERROR_SUCCESS) 
       bResult
=FALSE;
   
else
   {
       _splitpath(strPath.GetBuffer(
0),NULL,NULL,str.GetBufferSetLength(MAX_PATH+1),NULL);
       strPath.ReleaseBuffer();
       str.ReleaseBuffer();
       
if(::RegSetValueEx( hRegKey,
                           str,
                           
0,
                           REG_SZ,
                           (CONST BYTE 
*)strPath.GetBuffer(0),
                           strPath.GetLength() ) 
!= ERROR_SUCCESS)
          bResult
=FALSE;
       
else
          bResult
=TRUE;
       strPath.ReleaseBuffer();
   }
   
return bResult;
}        

 

使计算机休眠

void XiuMian() 
{
 
if(MessageBox("确实要休眠吗?","关机程序",MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION)==IDYES)
 {
  HANDLE hToken;
  TOKEN_PRIVILEGES tp;
  LUID luid;
  
if(::OpenProcessToken(GetCurrentProcess(),
         TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY,
         
&hToken))
  {
   ::LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,
&luid);
   tp.PrivilegeCount
=1;
   tp.Privileges[
0].Luid =luid;
   tp.Privileges[
0].Attributes =SE_PRIVILEGE_ENABLED;
   ::AdjustTokenPrivileges(hToken,
false,&tp,sizeof(TOKEN_PRIVILEGES),NULL,NULL);
  }
  ::SetSystemPowerState(
false,true); 
 }
}

posted @ 2006-07-15 01:01 紫雨轩 C++ 阅读(589) | 评论 (0)编辑 收藏

_ConnectionPtr m_pConnection;
 _CommandPtr m_pCommand;
.cpp中在函数中执行
// 建立ado连接
 HRESULT hr;
 hr
= m_pConnection.CreateInstance(__uuidof(Connection));
 
try
 {
 
if (SUCCEEDED(hr))
 {
 hr
= m_pConnection -> Open(_bstr_t(L " Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Viper;Data Source=Viper " ),_bstr_t (L " sa " ),_bstr_t (L "" ),adModeUnknown);
 }
 }
 
catch (_com_error  &  err)
 {
 AfxMessageBox(err.Description(),MB_OK,
0 );
 AfxMessageBox(err.ErrorMessage(),MB_OK,
0 );
 AfxMessageBox(
" 无法连接SQL SERVER 服务器,程序将退出。请检查网络设备 " ,MB_OK, 0 );
 exit(
0 );
 }

// 执行储存过程
 CString cvar1,cvar2;
 
int  cvar3;
 cvar1
= " ddd " ;
 cvar2
= "" ;
 cvar3
= 0 ;
 
try
 {
 m_pCommand.CreateInstance(__uuidof(Command));
 m_pCommand
-> ActiveConnection = app -> m_pConnection;
 m_pCommand
-> CommandType = adCmdStoredProc;
 m_pCommand
-> CommandText = _bstr_t( " pr_zs_dzdy " );

 _variant_t vvar1,vvar2,vvar3;
 vvar1
= _variant_t(_bstr_t(cvar1));
 vvar2
= _variant_t(_bstr_t(cvar2));
 vvar3
= _variant_t(cvar3);
 _ParameterPtr mp_var1,mp_var2,mp_var3;
 mp_var1.CreateInstance(__uuidof(Parameter));
 mp_var2.CreateInstance(__uuidof(Parameter));
 mp_var3.CreateInstance(__uuidof(Parameter));

 mp_var1
= m_pCommand -> CreateParameter
 (
 _bstr_t(
" var1 " ),
 adVarChar,
 adParamInput,
 
3 ,
vvar1
);
 m_pCommand
-> Parameters -> Append(mp_var1); 

 mp_var2
= m_pCommand -> CreateParameter
 (
 _bstr_t(
" var2 " ),
 adVarChar,
 adParamOutput,
 
3 ,
 vvar2
 );
 m_pCommand
-> Parameters -> Append(mp_var2); 

 mp_var3
= m_pCommand -> CreateParameter
 (
 _bstr_t(
" var3 " ),
 adIntger,
 adParamOutput,
 
9 ,
 vvar3
 );
 m_pCommand
-> Parameters -> Append(mp_var3); 


 _variant_t vNull;
 vNull.vt
= VT_ERROR;
 vNull.scode
= DISP_E_PARAMNOTFOUND;
 m_pCommand
-> Execute( & vNull, & vNull,adCmdStoredProc);
 cvar2
= mp_var2 -> Value.bstrVal;
 cvar3
= mp_var3 -> Value;
 }
 
catch (_com_error  & error)
 {
 MessageBox(error.ErrorMessage(),
" ADO错误! " );
 MessageBox(error.Description(),
" ADO错误! " );
 }

posted @ 2006-07-15 00:59 紫雨轩 C++ 阅读(2722) | 评论 (2)编辑 收藏

CString GetProcessorSeialNumbet( bool  withSeparator)
{
DWORD  t,m,b; 
// top,middle,botttom
DWORD *  serial;
  _asm
  {
    mov   eax,
1   // programmer: I need a Service ?
         
// processor: what type baby?
      
// eax = 3 --> 
       
// eax: top 32 bits are the processor signature bits
         

       
// programmer:this
    cpuid      // _emit 0x0f |cpuid mean this tow instruction
          
// _emit 0xa2 |instead of writing them 
       
//        
    
// mean:the sevice i want the processor serial number

 mov   t,eax 
//  top 32 bits are the processor signature bits
            /*  
          eax = 3 --> 
        ecx: middle 32 bits are the processor signature bits
         edx: bottom 32 bits are the processor signature bits
      
*/
    mov   eax,
3
    cpuid
    mov   m,edx
//  middle 32 bits are the processor signature bits
    mov   b,ecx //  bottom 32 bits are the processor signature bits
  }

  
//  copy the locals into the pointer variables passed in
  serial[ 0 =  b;
  serial[
1 =  m;
  serial[
2 =  t;


CString temp,SN;
SN.Empty();
static   char  hex_chars[ 16 =  { ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' ,
                 
' 8 ' , ' 9 ' , ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' };
for  ( int  dw_count  =   2 ; dw_count >= 0 ; dw_count -- )
  {
    
for  ( int  bp = 28 ; bp >= 0 ; bp -= 4 )
    {
      DWORD nibble 
=  (serial[dw_count]  >>  bp)  &   0x0f ;
      temp.Format(
" %c " , hex_chars[nibble]);
   SN
+= temp;
      
if  ((bp  ==   16 ||  ((bp  ==   0 &&  (dw_count != 0 )) )
    
if (withSeparator)SN += " - " ;
    }
  }
 
return  SN;
}

posted @ 2006-07-15 00:57 紫雨轩 C++ 阅读(623) | 评论 (0)编辑 收藏

GetActiveWindow返回线程的活动窗口,而不是系统的活动窗口。如果要得到用户正在激活的窗口,应该使用 GetForegroundWindow。

posted @ 2006-07-15 00:51 紫雨轩 C++ 阅读(3084) | 评论 (0)编辑 收藏

仅列出标题
共2页: 1 2 

posts - 18, comments - 22, trackbacks - 0, articles - 7

Copyright © 紫雨轩 C++