c利用句柄操作窗口.docx
《c利用句柄操作窗口.docx》由会员分享,可在线阅读,更多相关《c利用句柄操作窗口.docx(19页珍藏版)》请在冰豆网上搜索。
c利用句柄操作窗口
Documentnumber【980KGB-6898YT-769T8CB-246UT-18GG08】
c利用句柄操作窗口
C#
实现过程:
过程一:
找到当前鼠标位置的句柄
您的使用2个WinAPI(俺喜欢自己封装下来用):
ViewCode
[DllImport("",EntryPoint="GetCursorPos")]
publicstaticexternboolGetCursorPos(outPointpt);
[DllImport("",EntryPoint="WindowFromPoint")]
publicstaticexternIntPtrWindowFromPoint(Pointpt);
ndexOf;
}
publicoverridestringToString()
{
StringBuilderresult=newStringBuilder();
for(WinHWNDwinHandle=this;winHandle!
=null;winHandle=
{
("{0}:
{1};"
if==-1)break;
}
return().TrimEnd(';');
}
privatestaticstringGetBaseMark(stringsMark)
{
string[]sMarks=(';');
returnsMarks[-1].Split(':
')[0];
}
privatestaticstring[]GetChildMarks(stringsMark)
{
string[]sMarks=(';');
string[]sChildMarks=newstring[-1];
for(inti=0;i<;i++)
{
sChildMarks[i]=sMarks[i];
}
returnsChildMarks;
}
.是不是都匹配
foreach(IntPtrbaseHwndinbaseHwnds)
{
IntPtrhandle=baseHwnd;
for(inti=-1;i>=0;i--)
{
string[]sChildMark=sChildMarks[i].Split(':
');
try
{
handle=(handle,UnEscape(sChildMark[0]))[(sChildMark[1])];
}
catch
{
break;
}
if(i==0)returnnewWinHWND(handle);
}
continue;
}
returnnull;
}
#region转义
privatestaticstringEscape(stringarg)
{
return(":
","\\:
").Replace(";","\\;");
}
privatestaticstringUnEscape(stringarg)
{
return("\\:
",":
").Replace("\\;",";");
}
#endregion
publicstaticWinHWNDGetWinHWND()
{
returnnewWinHWND()));
}
}
上全部代码,里面加了窗口的部分属性,扩展其他的属性,自己发挥吧,就是搞WinAPI
ViewCode
usingSystem;
using
using;
using;
using
using;
using;
namespaceInformationCollectionDataFill
{
publicclassWinAPI
{
#regionWinodwsAPI
[DllImport("",EntryPoint="FindWindow")]
privatestaticexternIntPtrFindWindow(stringIpClassName,stringIpWindowName);
[DllImport("",EntryPoint="FindWindowEx")]
privatestaticexternIntPtrFindWindowEx(IntPtrhwndParent,IntPtrhwndChildAfter,stringlpszClass,stringlpszWindow);
[DllImport("",EntryPoint="SendMessage")]
privatestaticexternintSendMessage(IntPtrhWnd,intMsg,IntPtrwParam,stringlParam);
[DllImport("",EntryPoint="GetParent")]
publicstaticexternIntPtrGetParent(IntPtrhWnd);
[DllImport("",EntryPoint="GetCursorPos")]
publicstaticexternboolGetCursorPos(outPointpt);
[DllImport("",EntryPoint="WindowFromPoint",CharSet=,ExactSpelling=true)]
publicstaticexternIntPtrWindowFromPoint(Pointpt);
[DllImport("",CharSet=]
publicstaticexternintGetClassName(IntPtrhWnd,StringBuilderlpClassName,intnMaxCount);
[DllImport("",CharSet=]
publicstaticexternintGetWindowText(IntPtrhWnd,[Out,MarshalAs]StringBuilderlpString,intnMaxCount);
[DllImport("",CharSet=]
publicstaticexternintGetWindowRect(IntPtrhwnd,refRectanglerc);
[DllImport("",CharSet=]
publicstaticexternintGetClientRect(IntPtrhwnd,refRectanglerc);
[DllImport("",CharSet=]
publicstaticexternintMoveWindow(IntPtrhwnd,intx,inty,intnWidth,intnHeight,boolbRepaint);
[DllImport("",CharSet=,SetLastError=true,ExactSpelling=true)]
publicstaticexternintScreenToClient(IntPtrhWnd,refRectanglerect);
#endregion
#region封装API方法
ndexOf;
}
privateRectangleGetRect()
{
if==null)returndefault(Rectangle);
RectangleclientSize=;
RectangleclientPoint=);
returnnewRectangle,,,;
}
publicstaticWinHWNDGetWinHWND()
{
returnnewWinHWND()));
}
publicoverridestringToString()
{
StringBuilderresult=newStringBuilder();
for(WinHWNDwinHandle=this;winHandle!
=null;winHandle=
{
("{0}:
{1};"
if==-1)break;
}
return().TrimEnd(';');
}
privatestaticstringGetBaseMark(stringsMark)
{
string[]sMarks=(';');
returnsMarks[-1].Split(':
')[0];
}
privatestaticstring[]GetChildMarks(stringsMark)
{
string[]sMarks=(';');
string[]sChildMarks=newstring[-1];
for(inti=0;i<;i++)
{
sChildMarks[i]=sMarks[i];
}
returnsChildMarks;
}
.是不是都匹配
foreach(IntPtrbaseHwndinbaseHwnds)
{
IntPtrhandle=baseHwnd;
for(inti=-1;i>=0;i--)
{
string[]sChildMark=sChildMarks[i].Split(':
');
try
{
handle=(handle,UnEscape(sChildMark[0]))[(sChildMark[1])];
}
catch
{
break;
}
if(i==0)returnnewWinHWND(handle);
}
continue;
}
returnnull;
}
#region转义
privatestaticstringEscape(stringarg)
{
return(":
","\\:
").Replace(";","\\;");
}
privatestaticstringUnEscape(stringarg)
{
return("\\:
",":
").Replace("\\;",";");
}
#endregion
}
}
效果:
Postsubject:
DllInjection
Thisismyoldtutorialondllinjection...peoplehavebeenaskingaboutthistopicabitrecently,so...hereitis:
DllInjectionTutorial
byDarawk
Introduction
TheCreateRemoteThreadmethod
TheSetWindowsHookExmethod
Thecodecavemethod
AppendixA-MethodsofobtainingaprocessID
AppendixB-MethodsofobtainingathreadID
AppendixC-CompleteCreateRemoteThreadexamplesourcecode
AppendixD-CompleteSetWindowsHookExexamplesourcecode
AppendixE-Completecodecaveexamplesourcecode
Introduction
Inthistutoriali'lltrytocoveralloftheknownmethods(oratleast,thosethatIknow=p)ofinjectingdll'sintoaprocess.
DllinjectionisincrediblyusefulforTONSofstuff(gamehacking,functionhooking,codepatching,keygenning,unpacking,etc..).
Thoughtherearescatteredtutorialsonthesetechniquesavailablethroughouttheweb,Ihaveyettoseeanycompletetutorialsdetailing
allofthem(theremayevenbemoreouttherethanIhavehere,ofcourse),andcomparingtheirrespectivestrength'sandweakness's.
Thisispreciselywhati'llattempttodoforyouinthispaper.Youarefreetoreproduceorcopythispaper,solongasproper
creditisgivenandyoudon'tmodifyitwithoutspeakingtomefirst.
TheCreateRemoteThreadmethod
I'veusedthisintonsofstuff,andIonlyrecentlyrealizedthatalotofpeoplehaveneverseenit,orknowhowtodoit.
Ican'ttakecreditforthinkingitup...Igotitfromanarticleoncodeproject,butit'saneattrickthatIthinkmore
peopleshouldknowhowtouse.
Thetrickissimple,andelegant.ThewindowsAPIprovidesuswithafunctioncalledCreateRemoteThread().Thisallowsyou
tostartathreadinanotherprocess.Forourpurposes,i'llassumeyouknowhowthreadingworks,andhowtousefunctionslike
CreateThread(ifnot,youcangohere).ThemaindisadvantageofthismethodisthatitwillworkonlyonwindowsNTandabove.
Topreventitfromcrashing,youshouldusethisfunctiontochecktomakesureyou'reonanNT-basedsystem(thankstoCatIDfor
pointingthisout):
boolIsWindowsNT()
{
Now,normallywewouldwanttostartthethreadexecutingonsomeinternalfunctionoftheprocessthatweareinteractingwith.
However,toinjectadll,wehavetodosomethingalittlebitdifferent.
BOOLInjectDLL(DWORDProcessID)
{
HANDLEProc;
charbuf[50]={0};
LPVOIDRemoteString,LoadLibAddy;
if(!
ProcessID)
returnfalse;
Proc=OpenProcess(CREATE_THREAD_ACCESS,FALSE,ProcessID);
if(!
Proc)
{
sprintf(buf,"OpenProcess()failed:
%d",GetLastError());
MessageBox(NULL,buf,"Loader",NULL);
returnfalse;
}
LoadLibAddy=(LPVOID)GetProcAddress(GetModuleHandle(""),"LoadLibraryA");
RemoteString=(LPVOID)VirtualAllocEx(Proc,NULL,strlen(DLL_NAME),MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
WriteProcessMemory(Proc,(LPVOID)RemoteString,DLL_NAME,strlen(DLL_NAME),NULL);
CreateRemoteThread(Proc,NULL,NULL,(LPTHREAD_START_ROUTINE)LoadLibAddy,(LPVOID)RemoteString,NULL,NULL);?
?
CloseHandle(Proc);
returntrue;
}
HHOOKSetWindowsHookEx(?
intidHook,
HOOKPROClpfn,
HINSTANCEhMod,
DWORDdwThreadId
);
LRESULTCALLBACKCBTProc(intnCode,WPARAMwParam,LPARAMlParam)
{
returnCallNextHookEx(0,nCode,wParam,lParam);
};
HMODULEhDll;
unsignedlongcbtProcAddr;
hDll=LoadLibrary("");
cbtProcAddr=GetProcAddress(hDll,"CBTProc");
BOOLInjectDll(char*dllName)
{
HMODULEhDll;
unsignedlongcbtProcAddr;
hDll=LoadLibrary(dllName);
cbtProcAddr=GetProcAddress(hDll,"CBTProc");?
SetWindowsHookEx(WH_CBT,cbtProcAddr,hDll,GetTargetThreadIdFromWindow("targetApp"));
?
returnTRUE;
}
__declspec(naked)loadDll(void)
{
_asm{
Weneed
VirtualProtect(loadDll,stubLen,PAGE_EXECUTE_READWRITE,&oldprot);?
#defineCREATE_THREAD_ACCESS(PROCESS_CREATE_THREAD|PROCESS_QUERY_INFORMATION|PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ)
?
BOOLWriteProcessBYTES(HANDLEhProcess,LPVOIDlpBaseAddress,LPCVOIDlpBuffer,SIZE_TnSize);
BOOLLoadDll(char*procName,char*dllName);
BOOLInjectDLL(DWORDProcessID,char*dllName);
unsignedlongGetTargetProcessIdFromProcname(char*procName);
boolIsWindowsNT()
{
//checkcurrentversionofWindows
DWORDversion=GetVersion();
//parsereturn
DWORDmajorVersion=(DWORD)(LOBYTE(LOWORD(version)));
DWORDminorVersion=(DWORD)(HIBYTE(LOWORD(version)));
}
intWINAPIWinMain(HINSTANCEhInstance,HINSTANCEhPrevInstance,LPSTRlpCmdLine,intnCmdShow)
{
if(IsWindowsNT())
LoadDll(PROCESS_NAME,DLL_NAME);
else
MessageBox(0,"Yoursystemdoesnotsupportthismethod","Error!
",0);
return0;
}
BOOLLoadDll(char*procName,char*dllName)
{
DWORDProcID=0;
ProcID=GetProcID(procName);
if(!
(InjectDLL(ProcID,dllName)))
MessageBox(NULL,"Processlocated,butinjectionfailed","Loader",NULL);
?
returntrue;
}
BOOLInjectDLL(DWORDProcessID,char*dllName)
{
HANDLEProc;
charbuf[50]={0};
LPVOIDRemoteString,LoadLibAddy;
if(!
ProcessID)
returnfalse;
Proc=OpenProcess(CREATE_THREAD_ACCESS,FALSE,Proc