OSDN Git Service

マルチモニター環境で正常に動作しない時があった問題の修正
[dokopop/dokopop.git] / DCHook / DCHook.cpp
1 //---------------------------------------------------------------------------
2 //
3 // \96â\91è\93_\81F
4 // Ver0.50
5 //
6 // \8dÅ\93K\89»\82Ì\89Û\91è\81F
7 // standard library\82ð\8eg\82í\82È\82¢\82æ\82¤\82É\82·\82é
8 // \8b¤\97L\97Ì\88æ\82ð\91\9d\82â\82·
9 //
10 // Tips:
11 // \93Ë\91RDetach\82³\82ê\82é\8c»\8fÛ
12 // --> Hook Function\82Å\97á\8aO\82ª\94­\90\82µ\82Ä\82¢\82é\89Â\94\\90«\82ª\8d\82\82¢
13 //     \82à\82µ\82­\82Í\81A\83A\83v\83\8a\83P\81[\83V\83\87\83\93\82Å\97á\8aO\94­\90\82µ\82Ä\82¢\82é
14 // \8b¤\97L\83\81\83\82\83\8a\82É\82Â\82¢\82Ä
15 // \95¨\97\9d\83\81\83\82\83\8a\82ª\93¯\88ê\82¾\82¯\82Å\82 \82Á\82Ä\81A\98_\97\9d\83A\83h\83\8c\83X\82Í\93¯\88ê\82Æ\82Í\8cÀ\82ç\82È\82¢\81I\81I
16 // \8f]\82Á\82Ä\81A\8b¤\97L\83\81\83\82\83\8a\8fã\82Épointer\82ð\94z\92u\82·\82é\82±\82Æ\82Í\8aî\96{\93I\82É\8aë\8c¯\81I\81I
17 #define STRICT
18 #include <windows.h>
19 #include <tchar.h>
20 #pragma hdrstop
21 #ifndef GWL_WNDPROC
22 #define GWL_WNDPROC         (-4)        // \82±\82Ì\92è\8b`\82ª\82È\82¢\82Æerror\82É\82È\82Á\82½ 2014.11.19
23 #endif
24 #include <tlhelp32.h>
25 #include <imagehlp.h>
26 #pragma comment(lib, "ImageHlp")
27 #include "DCHook.h"
28 #ifndef UNICODE
29 #include "..\VxD\hk95d.h"
30 #endif
31 #include "MonitorScale.h"
32
33 // Compiler //
34 #pragma warning( disable : 4710 )       // \82Ç\82¤\82µ\82Ä\82±\82¤\82¢\82¤warning\82ª\8fo\82Ä\82­\82é\82Ì\82©\81H
35
36 // Configuration //
37 #define USE_SCALING             1       // Uses DPI scaling
38
39 #define USE_DBW                 1       // DBW\82ð\8eg\97p\82·\82é
40 #define USE_SHARE0              1       // share\82µ\82Ä\82à\96â\91è\82È\82¢\95Ï\90\94
41
42 #define METAEXTTEXTOUT  1       // MetaMethod\82ÅExtTextOutx\82ðhook\82·\82é
43 #define HOOK_GETDC              0       // GetDC(),ReleaseDC()\82ðhook\82·\82é
44 #define HOOK_TEXT               0       // DrawText(Ex),TextOut,TabbedTextOut\82Ìhooking
45 #define USE_REDRAW              1
46 #define HOOK_BITBLT             0       // 2016.1.15 \8aO\82µ\82Ä\82Ý\82½
47 #define HOOK_PAINT              0
48 #define GUARD                   0       // \8b¤\97L\83\81\83\82\83\8a\82ðVirtualProtect\82Åguard\82·\82é
49                                                         // \97L\8cø\82É\82·\82é\82ÆApplication\8fI\97¹\8e\9e\82É\88Ù\8fí\8fI\97¹\82ª\94­\90\82·\82é
50                             // Application close ->
51                             // \8c´\88ö\81FDettach\82·\82é\91O\82É\81AOS or Application\82ª
52                             // Protected code\97Ì\88æ\82É\8f\91\82«\8d\9e\82Ý\82ð\8ds\82Á\82Ä\82¢\82é\82æ\82¤\82¾
53
54 #define USE_INVALIDATE          0       // \95`\89æ\91O\82ÉInvalidate\82ð\91\97\82é(IE5@Win98\82Í\95K\97v)
55 #define INVALIDATE_TRUE         0       // InvalidateRect\82Årepaint\82ð\8ds\82¤
56 #define ORG_OFFSET                      1       // ViewPort\82Ìorg offset\8f\88\97\9d\82ð\8ds\82¤
57
58 #define USE_OPTIMALINVALID      1       // \8dÄ\95`\89æ\97Ì\88æ\82ð\82È\82é\82×\82­\8f¬\82³\82­\82·\82é
59 #define USE_VXD                         0       // no longer support (Win9x)
60 #define EXC_WOW64                       0       // do not attach on WOW64
61
62 #define MAX_KEYS                        8       // \83L\81[\83t\83\89\83O\82Ì\8dÅ\91å\92è\8b`\90\94
63
64 #define DEBUG_HITTEXT           0       // for debug hit text
65
66 // ExtTextOut hooking\82ÅMetafile\82à\8eg\97p\82·\82é
67 // \92P\93Æ\82Å\8ds\82¤\8fê\8d\87\82Í\81ARETRYMETA
68 #if HOOK_PAINT || HOOK_GETDC || !USE_REDRAW
69 #define USE_META        1
70 #else
71 #define USE_META        0
72 #endif
73
74 #define RETRYMETA       1
75
76 #if USE_DBW
77 #include <stdio.h>
78 #else   // !USE_DBW
79 #undef DEBUG_HITTEXT
80 #define DEBUG_HITTEXT   0
81 #endif  // !USE_DBW
82
83 #define MOVESEND_POST   1
84
85 // Type Definitions //
86
87 // Macros //
88 #if GUARD
89 #define PROTECT_SHARE()         ShareProtect( true )
90 #define UNPROTECT_SHARE()       ShareProtect( false )
91 #else
92 #define PROTECT_SHARE()
93 #define UNPROTECT_SHARE()
94 #endif
95
96 #if USE_DBW
97 #define DBW             dbw
98 #else
99 #define DBW             (void)
100 #endif
101 void dbw(const char *format, ...);
102
103 #define WM_AMODI                                (WM_APP+0x400)  // app communication message with AMODI
104 #define WM_MOVESEND                             (WM_APP+0x208)  // DCH_MOVESEND\82Ì\91ã\82í\82è\82ÉPostMessage\82Å\91\97\82é
105 #define AMODI_CMD_QUERY                 0
106 #define AMODI_CMD_PAGE_CAPTURE  1
107
108 #define tsizeof(type)   sizeof(type)
109 #define int_bool(v)             ((v)!=0)
110
111 #pragma warning (disable : 4996)
112
113 //==============================================//
114 // TString template class                                               //
115 //==============================================//
116 template <class T>
117 class TString {
118 protected:
119         T *Buffer;
120         int Size;       // Buffer size in character
121         int Length;     // String length in character
122 public:
123         TString();
124         ~TString();
125         void Clear()
126                 { Buffer[0] = '\0'; Length = 0; }
127         void Set( const T *str, int len );
128         void Set( TString *obj )
129                 { Set( obj->c_str(), obj->Length ); }
130         void Cat( const T *str, int len );
131         operator const T *() const
132                 { return Buffer; }
133         T operator [] ( int index )
134                 { return Buffer[index]; }
135         const T *c_str()
136                 { return Buffer; }
137         int GetLength() const { return Length; }
138         int GetByte() const { return Length * sizeof(T); }
139 //      int GetSize() const { return Size; }
140 };
141 template <class T>
142 TString<T>::TString()
143 {
144         Size = 256;             // initial size
145         Buffer = new T[ Size + 1 ];
146         if (!Buffer)
147                 Size = 0;
148         Length = 0;
149 }
150 template <class T>
151 TString<T>::~TString()
152 {
153         if (Buffer)
154                 delete[] Buffer;
155 }
156 template <class T>
157 void TString<T>::Set( const T *str, int len )
158 {
159         if (Buffer){
160                 if ( Size < len ){
161                         // not enough space to store
162                         delete[] Buffer;
163                 } else goto j1;
164         }
165         Buffer = new T[ len + 1 ];
166         Size = len;
167         if (Buffer){
168 j1:;
169                 CopyMemory( Buffer, str, len*sizeof(T) );
170                 Buffer[len] = '\0';
171                 Length = len;
172         } else {
173                 Size = 0;
174                 Length = 0;
175         }
176 }
177 template <class T>
178 void TString<T>::Cat( const T *str, int len )
179 {
180         if (!Buffer){
181                 Set( str, len );
182                 return;
183         }
184         int newlen = Length + len;
185         if (Size < newlen){
186                 T *p = new T[ newlen + 1 ];
187                 if (p)
188                         CopyMemory( p, Buffer, newlen*sizeof(T) );
189                 delete[] Buffer;
190                 Buffer = p;
191                 Size = newlen;
192         }
193         if (Buffer){
194                 CopyMemory( Buffer+Length, str, len * sizeof(T) );
195                 Buffer[newlen] = '\0';
196                 Length = newlen;
197         } else {
198                 Size = 0;
199                 Length = 0;
200                 Set( str, len );
201         }
202 }
203
204 int GetTextFromPoint( HDC hdc, const char *text, int len, int pos, int pos_y, const int *dx=NULL );
205 int GetTextFromPoint( HDC hdc, const wchar_t *text, int len, int pos, int pos_y, const int *dx=NULL );
206
207 bool CaptureImage(HWND hwnd, bool movesend, bool non_block);
208 bool WaitAndGetResult(const TCHAR *text_path, unsigned waittime);
209 HANDLE WaitForResult(const TCHAR *text_path, unsigned waittime);
210 HWND FindAMODI();
211 int SendAMODI(int cmd, const char *data, int len);
212 void CheckAMODIAlive();
213 void SendMoveMessage();
214 void SendCancelMove();
215 DWORD WINAPI SendMoveThread(LPVOID vdParam);
216 void CheckWOW64();
217
218 extern "C" {
219 //==============================================//
220 // Prototypes                                                                   //
221 //==============================================//
222 typedef HDC (WINAPI *FNBeginPaint)( HWND, LPPAINTSTRUCT );
223 typedef BOOL (WINAPI *FNEndPaint)( HWND, CONST PAINTSTRUCT * );
224 typedef HDC (WINAPI *FNGetDC)( HWND );
225 typedef int (WINAPI *FNReleaseDC)( HWND, HDC );
226 typedef BOOL (WINAPI *FNExtTextOutW)(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCWSTR str, UINT count, CONST INT *dx );
227 typedef BOOL (WINAPI *FNExtTextOutA)(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCSTR str, UINT count, CONST INT *dx );
228 typedef BOOL (WINAPI *FNBitBlt)(HDC hdcdest, int xdest, int ydest, int width, int height, HDC hdcsrc, int xsrc, int ysrc, DWORD rop );
229
230 typedef LONG (WINAPI *FNTabbedTextOutA)( HDC hdc, int x, int y, LPCSTR str, int count, int ntabs, LPINT tabs, int origin );
231 typedef LONG (WINAPI *FNTabbedTextOutW)( HDC hdc, int x, int y, LPCWSTR str, int count, int ntabs, LPINT tabs, int origin );
232 typedef BOOL (WINAPI *FNTextOutA)( HDC hdc, int x, int y, LPCSTR str, int count );
233 typedef BOOL (WINAPI *FNTextOutW)( HDC hdc, int x, int y, LPCWSTR str, int count );
234 typedef int (WINAPI *FNDrawTextA)( HDC hdc, LPCSTR str, int count, LPRECT rc, UINT format );
235 typedef int (WINAPI *FNDrawTextW)( HDC hdc, LPCWSTR str, int count, LPRECT rc, UINT format );
236 typedef int (WINAPI *FNDrawTextExA)( HDC hdc, LPCSTR str, int count, LPRECT rc, UINT format, LPDRAWTEXTPARAMS params );
237 typedef int (WINAPI *FNDrawTextExW)( HDC hdc, LPCWSTR str, int count, LPRECT rc, UINT format, LPDRAWTEXTPARAMS params );
238
239 typedef BOOL (WINAPI *FNMoveToEx)(HDC hdc, int x, int y, LPPOINT pt );
240
241
242 HDC WINAPI _BeginPaint( HWND hwnd, LPPAINTSTRUCT ps );
243 BOOL WINAPI _EndPaint( HWND hwnd, CONST PAINTSTRUCT *ps );
244 HDC WINAPI _GetDC( HWND hwnd );
245 int WINAPI _ReleaseDC( HWND hwnd, HDC hdc );
246 BOOL  WINAPI _ExtTextOutA(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCSTR str, UINT count, CONST INT *dx );
247 BOOL  WINAPI _ExtTextOutW(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCWSTR str, UINT count, CONST INT *dx );
248 BOOL WINAPI _BitBlt(HDC hdcdest, int xdest, int ydest, int width, int height, HDC hdcsrc, int xsrc, int ysrc, DWORD rop );
249
250 LONG WINAPI _TabbedTextOutA( HDC hdc, int x, int y, LPCSTR str, int count, int ntabs, LPINT tabs, int origin );
251 LONG WINAPI _TabbedTextOutW( HDC hdc, int x, int y, LPCWSTR str, int count, int ntabs, LPINT tabs, int origin );
252 BOOL WINAPI _TextOutA( HDC hdc, int x, int y, LPCSTR str, int count );
253 BOOL WINAPI _TextOutW( HDC hdc, int x, int y, LPCWSTR str, int count );
254 int WINAPI _DrawTextA( HDC hdc, LPCSTR str, int count, LPRECT rc, UINT format );
255 int WINAPI _DrawTextW( HDC hdc, LPCWSTR str, int count, LPRECT rc, UINT format );
256 int WINAPI _DrawTextExA( HDC hdc, LPCSTR str, int count, LPRECT rc, UINT format, LPDRAWTEXTPARAMS params );
257 int WINAPI _DrawTextExW( HDC hdc, LPCWSTR str, int count, LPRECT rc, UINT format, LPDRAWTEXTPARAMS params );
258
259 BOOL WINAPI _MoveToEx( HDC hdc, int x, int y, LPPOINT pt );
260
261 void ShareProtect( bool f );
262 DWORD SetWriteProtect( LPVOID addr, bool f );
263 bool ChangeMemory( void *dst, const void *src, unsigned size );
264 bool LoadVxD();
265 void UnloadVxD();
266
267 static HMODULE ModuleFromAddress(PVOID pv);
268
269 // Prototypes for PSAPI.DLL //
270 typedef BOOL (WINAPI *FNEnumProcessModules)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
271 typedef DWORD (WINAPI *FNGetModuleFileNameExA)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
272 typedef HANDLE (WINAPI *FNCreateToolhelp32Snapshot)( DWORD dwFlags, DWORD th32ProcessID );
273 typedef BOOL (WINAPI *FNModule32First)( HANDLE hSnapshot, LPMODULEENTRY32 lpme );
274 typedef BOOL (WINAPI *FNModule32Next)( HANDLE hSnapshot, LPMODULEENTRY32 lpme );
275
276
277 LRESULT CALLBACK MouseProc( int code, WPARAM wParam, LPARAM lParam );
278 LRESULT CALLBACK KeyboardProc( int code, WPARAM wParam, LPARAM lParam );
279 bool CaptureText( HWND hwnd, bool movesend );
280 bool DoCapture(HWND hwnd, POINT pt, bool movesend, bool image_only=false, bool runOnLaunchedProc=false, bool nonBlock=false);
281 void DokoPopMenu( HWND hwnd );
282 void ToggleClick( HWND hwnd );
283 int CALLBACK EnumMetaFileProc( HDC hdc, HANDLETABLE *, CONST ENHMETARECORD *mfr, int nobj, LPARAM user );
284
285 //__declspec(dllexport)
286 BOOL  WINAPI _ExtTextOutA(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCSTR str, UINT count, CONST INT *dx );
287
288 #if METAEXTTEXTOUT
289 void ExtTextOutHit();
290 #endif
291
292 void DoScale(HDC hdc, POINT *pts, int num);
293
294 // Prototypes for High DPI //
295 typedef enum _PROCESS_DPI_AWARENESS { 
296   Process_DPI_Unaware            = 0,
297   Process_System_DPI_Aware       = 1,
298   Process_Per_Monitor_DPI_Aware  = 2
299 } PROCESS_DPI_AWARENESS;
300
301 typedef HRESULT (WINAPI *FNGetProcessDPIAwareness)(HANDLE hprocess, PROCESS_DPI_AWARENESS *value);
302 typedef HRESULT (WINAPI *FNSetProcessDPIAwareness)(PROCESS_DPI_AWARENESS value);
303
304 //==============================================//
305 // Shared Section                                                               //
306 //==============================================//
307 #pragma data_seg(".sdata")
308 #pragma bss_seg( ".sbss" )
309 HWND hwndCallback = NULL;
310 #if USE_VXD
311 char VxDpathName[256];  // HK95.vxd path
312 #endif
313 DWORD siPageSize = 0;
314 HWND hwndOrg = NULL;
315 HWND hwndAMODI = NULL;
316 bool OnlyAMODI = false;
317 bool tryAMODI = false;
318 bool MoveSend = false;
319 #if USE_DBW
320 int attach = 0;
321 #endif
322 #if USE_VXD
323 bool WindowsNT;
324 #else
325 const bool WindowsNT = true;
326 #endif
327 bool Initialized = false;       // Whether this module initialized or not
328 DWORD idDokopopProcess;         // DKPP.EXE process ID
329 HHOOK hMouseHook;       // Windows Hook Handle for mouse
330 bool ClickOnlyEnabled = false;
331
332 struct TKeyConfig {
333         unsigned char Action;
334         int Flag;
335 };
336
337 TKeyConfig KeyConfig[MAX_KEYS] = {
338         { KA_POPUP, KF_CONTROL },                       // Ctrl+click
339         { KA_POPUP_NC, KF_CLICKONLY },                  // click\82¾\82¯\82Åpopup(DO NOT CHANGE)
340 //      { KA_MENU, KF_CONTROL | KF_MENU },      // dokopop menu
341 //      { KA_MENU, KF_CONTROL | KF_MENU | KF_CLICKONLY },       // dokopop menu
342         { KA_TOGGLE, KF_CONTROL | KF_MENU },    // dokopop menu
343         { 0, 0 }
344 };
345
346 bool fWow64 = false;
347
348 POINT CursorPoint;      // Client area coordinate //
349 POINT ScreenPoint;      // Screen coordinate //
350 POINT PrevCursorPoint;
351 HWND hwndLast = NULL;
352 DWORD PrevMoveTime = 0;
353 bool MoveSent = true;
354 bool OnlyImage = false;
355
356 bool MouseMoving;
357
358 RECT rcClient;
359 RECT rcInvalid;
360 RECT rcOrgInvalid;      // \8dÄ\95`\89æ\91O\82Éinvalid\82¾\82Á\82½\97Ì\88æ
361 bool HitFound;
362 bool RButtonUpCancel = false;   // \8e\9f\82ÌRButtonUp\82Í\94j\8aü\82·\82é
363 bool LButtonUpCancel = false;   // \8e\9f\82ÌLButtonUp\82Í\94j\8aü\82·\82é
364 bool MButtonUpCancel = false;   // \8e\9f\82ÌMButtonUp\82Í\94j\8aü\82·\82é
365 bool LButtonDown = false;
366 bool MButtonDown = false;
367
368 HINSTANCE hPSAPI;               // handle of PSAPI.DLL(NT only)
369 FNEnumProcessModules fnEnumProcessModules;
370 FNGetModuleFileNameExA fnGetModuleFileNameExA;
371 FNCreateToolhelp32Snapshot fnCreateToolhelp32Snapshot;
372 FNModule32First fnModule32First;
373 FNModule32Next fnModule32Next;
374
375 #if USE_META || RETRYMETA
376 HDC OrgHDC;
377 HDC hdcMeta;
378 #endif
379 HDC hdcExtTextOut;
380 #if HOOK_GETDC
381 HDC OrgGetDC;
382 #endif
383
384 int BitBltCount;                // \8c»\8dÝ\82ÌBitBlt\89ñ\90\94
385 int ExtTextOutCount;    // \8c»\8dÝ\82ÌBand\93à\82ÌExtTextOut\89ñ\90\94(A/W\82Æ\82à)
386 int TargetBitBltCount;  // \8c\9f\8d¸\91Î\8fÛ\82ÌBitBlt(\8f\89\89ñ\95`\89æ\8cã\82É\94»\92è) 
387 POINT TargetOffset;             // \8c\9f\8d¸\91Î\8fÛ\82ÌBitBlt\82Ì\95`\89æ\83I\83t\83Z\83b\83g(\8f\89\89ñ\95`\89æ\8cã\82É\94»\92è)
388 bool RetryPhase;
389
390 #if METAEXTTEXTOUT
391 // hit text information
392 TString<char> *FoundTextA;
393 TString<wchar_t> *FoundTextW;
394 int FoundLocA;
395 int FoundLocW;
396
397 // \8dÅ\8cã\82É\95`\89æ\82µ\82½\83e\83L\83X\83g\82Ì\8fî\95ñ
398 // for text merge
399 int LastX;      // \8dÅ\8cã\82É\95`\89æ\82µ\82½\83e\83L\83X\83g\82Ì\89E\8fã\8dÀ\95W
400 int LastY;
401 TString<char> *LastTextA;
402 TString<wchar_t> *LastTextW;
403 #endif  // METAEXTTEXTOUT
404
405 bool MoveSendMode;
406
407 TCHAR AMODIPath[256];
408 bool ExtAMODI = false;
409 int ScaleX = 0; // 96\82ð1\82Æ\82µ\82½\89æ\96Ê\82Ì\8ag\91å\97¦
410 int ScaleY = 0;
411 int generation = 0;
412
413 TCHAR ImageTextPath[256+40];    // OCR\97pimage filename or text filename
414 DWORD SaveImageTime;
415 bool CaptureImageBlocking = false;
416
417 const char STR_USER32[] = "user32.dll";
418 const char STR_GDI32[] = "gdi32.dll";
419 const char STR_KERNEL32[] = "kernel32.dll";
420 const TCHAR STR_PSAPI[] = _T("psapi.dll");
421
422 // KERNEL32.DLL //
423 const char STR_CreateToolhelp32Snapshot[] = "CreateToolhelp32Snapshot";
424 const char STR_Module32First[] = "Module32First";
425 const char STR_Module32Next[] = "Module32Next";
426
427 // PSAPI.DLL //
428 const char STR_EnumProcessModules[] = "EnumProcessModules";
429 const char STR_GetModuleFileNameExA[] = "GetModuleFileNameExA";
430
431 const char STR_BeginPaint[] = "BeginPaint";
432 const char STR_EndPaint[] = "EndPaint";
433 const char STR_BitBlt[] = "BitBlt";
434 const char STR_GetDC[] = "GetDC";
435 const char STR_ReleaseDC[] = "ReleaseDC";
436
437 const char STR_ExtTextOutA[] = "ExtTextOutA";
438 const char STR_ExtTextOutW[] = "ExtTextOutW";
439 const char STR_TabbedTextOutA[] = "TabbedTextOutA";
440 const char STR_TabbedTextOutW[] = "TabbedTextOutW";
441 const char STR_TextOutA[] = "TextOutA";
442 const char STR_TextOutW[] = "TextOutW";
443 const char STR_DrawTextA[] = "DrawTextA";
444 const char STR_DrawTextW[] = "DrawTextW";
445 const char STR_DrawTextExA[] = "DrawTextExA";
446 const char STR_DrawTextExW[] = "DrawTextExW";
447
448 #if USE_SHARE0
449 #pragma data_seg()
450 #pragma bss_seg()
451 #endif
452
453 //==============================================//
454 // Module depend values                                                 //
455 //==============================================//
456 HINSTANCE hInstance;    // attached instance
457 DWORD idProcess;                // attached process
458 HANDLE hProcess;        // Hook\8e\9eGetCurrentProcess()\82Í\8eg\82¦\82È\82¢
459                                         // Hook\8e\9e\82Ìcurrent process\82ª\8f\91\82«\8a·\82¦\82½\82¢thunk\82Ìprocess\82Æ\88ê\92v\82·\82é\82Æ\82Í\8cÀ\82ç\82È\82¢\82½\82ß
460                                         // \82»\82Ì\82½\82ß\81ADLL\82Ìattach\8e\9e\82ÉWriteProcessMemory()\97p\82Éprocess handle\82ð\8eæ\93¾\82·\82é
461 DWORD curProcess;       // hooking process
462 #if USE_VXD
463 HANDLE vxd_Handle = INVALID_HANDLE_VALUE;       // Not shared
464 #endif
465
466 #if !MOVESEND_POST
467 HANDLE SendMoveEvent = NULL;
468 DWORD SendMoveThreadId;
469 #endif
470
471 HINSTANCE hInstSHCore = NULL;
472 FNGetProcessDPIAwareness GetProcessDPIAwareness = NULL;
473
474 //==============================================//
475 // APIHOOK                                                                              //
476 //==============================================//
477 class APIHOOK {
478 public:
479         const char *ModName;
480         const char *FuncName;
481 protected:
482         bool ExcludeMe;
483         bool Hooked;
484 public:
485         PROC OrgFunc;   // not shared@NT
486 protected:
487         PROC HookFunc;  // not shared
488         // Process dedicated values //
489 public:
490         static void *MaxAppAddr;        // Maximum private memory address
491 protected:
492         static APIHOOK *LinkTop;        // top of APIHOOK link
493         APIHOOK *LinkNext;                      // next pointer of API HOOK link
494 public:
495         APIHOOK( const char *modname, const char *name, void *hookfunc, bool excme = true );
496         ~APIHOOK();
497         bool GetProcOrgFunc( HINSTANCE hInst );
498         bool GetProcOrgFunc();
499         bool HookAgain();
500         void Finish();
501 protected:
502         bool StoreCode( );
503         void RestoreCode( );
504 protected:
505         static void ReplaceIATEntryInAllMods( APIHOOK *obj, PROC pfnCurrent, PROC pfnNew );
506         static bool ReplaceIATEntryInOneMod( APIHOOK *obj, PROC pfnCurrent, PROC pfnNew, HMODULE hmodCaller);
507 };
508
509 const BYTE cPushOpCode = 0x68;   // The PUSH opcode on x86 platforms
510 APIHOOK* APIHOOK::LinkTop = NULL;
511 PVOID APIHOOK::MaxAppAddr = NULL;
512
513 APIHOOK::APIHOOK( const char *modname, const char *funcname, void *hookfunc, bool excme )
514 {
515 //      DBW("APIHOOK constructor:%08X %s %s",this, modname, funcname);
516         Hooked = false;
517         ModName = modname;
518         FuncName = funcname;
519         HookFunc = (PROC)hookfunc;
520         ExcludeMe = excme;
521         LinkNext  = LinkTop;
522         LinkTop = this;
523         if (!MaxAppAddr){
524                 // Functions with address above lpMaximumApplicationAddress require
525                 // special processing (Windows 98 only)
526                 SYSTEM_INFO si;
527                 GetSystemInfo(&si);
528                 MaxAppAddr = si.lpMaximumApplicationAddress;
529         }
530 }
531
532 APIHOOK::~APIHOOK()
533 {
534         Finish();
535         // Remove this object from the linked list
536         APIHOOK* p = LinkTop;
537         if (p == this) {     // Removing the head node
538                 LinkTop = p->LinkNext;
539         } else {
540                 // Walk list from head and fix pointers
541                 for (; p->LinkNext; p = p->LinkNext){
542                         if (p->LinkNext == this) {
543                                 // Make the node that points to us point to the our next node
544                                 p->LinkNext = p->LinkNext->LinkNext;
545                                 break;
546                         }
547                 }
548         }
549 }
550 bool APIHOOK::GetProcOrgFunc()
551 {
552         return GetProcOrgFunc( GetModuleHandleA( ModName ) );
553 }
554 bool APIHOOK::GetProcOrgFunc( HINSTANCE hInst )
555 {
556         if (Hooked) return true;
557
558         // Save information about this hooked function
559         OrgFunc = ::GetProcAddress( hInst, FuncName);
560         if (!OrgFunc){
561                 DBW("Function doesn't exist =%s:%s", ModName, FuncName);
562                 return false;
563         }
564
565         if (OrgFunc > MaxAppAddr) {
566 //              DBW("The address is in a shared DLL; the address needs fixing up");
567                 PBYTE pb = (PBYTE)OrgFunc;
568                 if (pb[0] == cPushOpCode){
569                         // Skip over the PUSH op code and grab the real address
570                         PVOID pv = * (PVOID*) &pb[1];
571                         OrgFunc = (PROC) pv;
572                 }
573         }
574
575         // Set assembler code for hooking at the org entry
576         if ( !StoreCode() ){
577                 DBW("Cannot write process memory");
578                 return false;
579         }
580
581         Hooked = true;
582         return true;
583 }
584 bool APIHOOK::StoreCode( )
585 {
586         DBW("StoreCode:%s %s", ModName, FuncName);
587         // Hook this function in all currently loaded modules
588         ReplaceIATEntryInAllMods( this, OrgFunc, HookFunc );
589         return true;
590 }
591 void APIHOOK::RestoreCode()
592 {
593         DBW("RestoreCode:%s %s", ModName, FuncName);
594         ReplaceIATEntryInAllMods( this, HookFunc, OrgFunc );
595 }
596 void APIHOOK::ReplaceIATEntryInAllMods( APIHOOK *obj, PROC pfnCurrent, PROC pfnNew )
597 {
598         HMODULE hmodThisMod = obj->ExcludeMe
599                 ? ModuleFromAddress(ReplaceIATEntryInAllMods) : NULL;
600
601         DWORD cbNeeded;
602         HMODULE hMods[1024];
603         unsigned i;
604         if (fnCreateToolhelp32Snapshot){
605                 // Toolhelp\82ª\8eg\97p\82Å\82«\82é\8fê\8d\87\82Í\8eg\97p\82·\82é
606                 // Get the list of modules in this process
607                 HANDLE hSnapshot = fnCreateToolhelp32Snapshot(TH32CS_SNAPMODULE, idProcess);
608
609                 MODULEENTRY32 me = { sizeof(me) };
610                 for (BOOL fOk = fnModule32First(hSnapshot,&me); fOk; fOk = fnModule32Next(hSnapshot,&me)){
611                         // NOTE: We don't hook functions in our own module
612                         if (me.hModule != hmodThisMod){
613         //                      DBW("Module : %s %s", me.szModule,FuncName);
614                                 // Hook this function in this module
615                                 ReplaceIATEntryInOneMod( obj, pfnCurrent, pfnNew, me.hModule);
616                         }
617                 }
618                 CloseHandle( hSnapshot );
619         } else {
620                 if( fnEnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
621                 {
622                         for ( i = 0; i < (cbNeeded / sizeof(HMODULE)); i++ )
623                         {
624                                 if (hMods[i] != hmodThisMod){
625                                         char szModName[MAX_PATH];
626                                         // Get the full path to the module's file.
627                                         if ( fnGetModuleFileNameExA( hProcess, hMods[i], szModName,
628                                                                                 sizeof(szModName))){
629         //                                      DBW("Module : %s %s", szModName, FuncName );
630                                                 ReplaceIATEntryInOneMod( obj, pfnCurrent, pfnNew, hMods[i]);
631                                         }
632                                 }
633                         }
634                 }
635 #if USE_DBW
636                 else DBW("EnumProcessModules failed");
637 #endif
638         }
639 }
640
641 // This functions is almost taken from Jeffrey Richter's sample, thank you.
642 bool APIHOOK::ReplaceIATEntryInOneMod( APIHOOK *obj, PROC pfnCurrent, PROC pfnNew, HMODULE hmodCaller)
643 {
644         if (!hProcess) return false;
645
646         // Get the address of the module's import section
647         ULONG ulSize;
648         PIMAGE_IMPORT_DESCRIPTOR pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)
649                 ImageDirectoryEntryToData(hmodCaller, TRUE,
650                         IMAGE_DIRECTORY_ENTRY_IMPORT, &ulSize);
651
652         if (!pImportDesc){
653 //              DBW("No import section : %s", obj->ModName);
654                 return false;
655         }
656
657         // Find the import descriptor containing references to callee's functions
658         for (; pImportDesc->Name; pImportDesc++){
659                 PSTR pszModName = (PSTR) ((PBYTE) hmodCaller + pImportDesc->Name);
660                 if (lstrcmpiA(pszModName, obj->ModName) == 0) 
661                         break;   // Found
662         }
663
664         if (pImportDesc->Name == 0){
665 //              DBW("This module doesn't import any functions from this callee");
666                 return false;  // This module doesn't import any functions from this callee
667         }
668
669    // Get caller's import address table (IAT) for the callee's functions
670         PIMAGE_THUNK_DATA pThunk = (PIMAGE_THUNK_DATA) 
671                 ((PBYTE) hmodCaller + pImportDesc->FirstThunk);
672
673         // Replace current function address with new function address
674         for (; pThunk->u1.Function; pThunk++){
675                 // Get the address of the function address
676                 PROC* ppfn = (PROC*) &pThunk->u1.Function;
677                 // Is this the function we're looking for?
678                 BOOL fFound = (*ppfn == pfnCurrent);
679                 if (!fFound && (*ppfn > MaxAppAddr)){
680                         // If this is not the function and the address is in a shared DLL, 
681                         // then maybe we're running under a debugger on Windows 98. In this 
682                         // case, this address points to an instruction that may have the 
683                         // correct address.
684                         PBYTE pbInFunc = (PBYTE) *ppfn;
685                         if (pbInFunc[0] == cPushOpCode){
686                                 // We see the PUSH instruction, the real function address follows
687                                 ppfn = (PROC*) &pbInFunc[1];
688
689                                 // Is this the function we're looking for?
690                                 fFound = (*ppfn == pfnCurrent);
691                         }
692                 }
693
694                 if (fFound){
695                         // The addresses match, change the import section address
696                         if (!WriteProcessMemory(hProcess, ppfn, &pfnNew, sizeof(pfnNew), NULL)){
697                                 if (SetWriteProtect( (LPVOID)ppfn, false )==~0){        // write protection release
698                                         DBW("SetWriteProtect failed: %08X %s %s", ppfn, obj->ModName, obj->FuncName);
699                                         return false;
700                                 }
701 #if USE_VXD
702                                 if (!WindowsNT && IsBadWritePtr(ppfn,sizeof(pfnNew))){
703                                         // Windows9x shared DLL section
704                                         // change memory attribte using VxD
705                                         if (!ChangeMemory( ppfn, &pfnNew, sizeof(pfnNew) )){
706                                                 DBW("ChangeMemory failed");
707                                         }
708                                 } else
709 #endif
710                                 {
711                                         if (!WriteProcessMemory(hProcess, ppfn, &pfnNew, sizeof(pfnNew), NULL)){
712                                                 //SetWriteProtect( ppfn, true );        // restore protection
713                                                 DBW("%08X %08X %08X %08X %s %s", hProcess, ppfn, &pfnNew, sizeof(pfnNew), obj->ModName, obj->FuncName );
714                                                 DBW("WriteProcessMemory failed : %d",GetLastError());
715                                                 return false;
716                                         }
717                                 }
718                         }
719                         return true;  // We did it, get out
720                 }
721         }
722
723         //DBW("Not found");
724
725         // If we get to here, the function is not in the caller's import section
726         return false;
727 }
728 bool APIHOOK::HookAgain()
729 {
730         if ( Hooked ) return true;
731
732         // Set assembler code for hooking at the org entry
733         if ( !StoreCode() ){
734                 DBW("Cannot write process memory@rehook");
735                 return false;
736         }
737
738         Hooked = true;
739         return true;
740 }
741 void APIHOOK::Finish()
742 {
743         if ( !Hooked ) return;
744         RestoreCode();
745         Hooked = false;
746 }
747 // Returns the HMODULE that contains the specified memory address
748 static HMODULE ModuleFromAddress(PVOID pv)
749 {
750         MEMORY_BASIC_INFORMATION mbi;
751         return((VirtualQuery(pv, &mbi, sizeof(mbi)) != 0) 
752                 ? (HMODULE) mbi.AllocationBase : NULL);
753 }
754
755 #if HOOK_PAINT || RETRYMETA
756 APIHOOK BeginPaintHook( STR_USER32, STR_BeginPaint, _BeginPaint );
757 APIHOOK EndPaintHook( STR_USER32, STR_EndPaint, _EndPaint );
758 #endif
759
760 #if HOOK_BITBLT
761 APIHOOK BitBltHook( STR_GDI32, STR_BitBlt, _BitBlt );
762 #endif
763
764 #if HOOK_GETDC
765 APIHOOK GetDCHook( STR_USER32, STR_GetDC, _GetDC );
766 APIHOOK ReleaseDCHook( STR_USER32, STR_ReleaseDC, _ReleaseDC );
767 #endif
768
769 #if METAEXTTEXTOUT
770 APIHOOK ExtTextOutAHook( STR_GDI32, STR_ExtTextOutA, _ExtTextOutA );
771 APIHOOK ExtTextOutWHook( STR_GDI32, STR_ExtTextOutW, _ExtTextOutW );
772 #if HOOK_TEXT
773 APIHOOK TabbedTextOutAHook( STR_USER32, STR_TabbedTextOutA, _TabbedTextOutA );
774 APIHOOK TabbedTextOutWHook( STR_USER32, STR_TabbedTextOutW, _TabbedTextOutW );
775 APIHOOK TextOutAHook( STR_GDI32, STR_TextOutA, _TextOutA );
776 APIHOOK TextOutWHook( STR_GDI32, STR_TextOutW, _TextOutW );
777 APIHOOK DrawTextAHook( STR_USER32, STR_DrawTextA, _DrawTextA );
778 APIHOOK DrawTextWHook( STR_USER32, STR_DrawTextW, _DrawTextW );
779 APIHOOK DrawTextExAHook( STR_USER32, STR_DrawTextExA, _DrawTextExA );
780 APIHOOK DrawTextExWHook( STR_USER32, STR_DrawTextExW, _DrawTextExW );
781 #endif
782 #endif  // METAEXTTEXTOUT
783
784 __declspec(dllexport)
785 bool WINAPI Init( HWND _hwnd, const char * /*module_name*/, bool windowsnt, const char *vxd_path )
786 {
787         DBW("Init:%08X %d", _hwnd, windowsnt);
788         hwndCallback = _hwnd;
789         if ( Initialized ){
790                 return true;
791         }
792 #if USE_VXD
793         WindowsNT = windowsnt;
794         if (vxd_path){
795 //              DBW("vxd_path=%s",vxd_path);
796                 lstrcpy( VxDpathName, "\\\\.\\" );
797                 lstrcat( VxDpathName, vxd_path );
798                 if (!LoadVxD()){
799                         DBW("Cannot open VxD:%s:%d", VxDpathName,GetLastError() );
800                         return false;
801                 }
802         }
803 #endif
804
805 //      HINSTANCE hDll = GetModuleHandle( module_name );
806         hMouseHook = SetWindowsHookEx( WH_MOUSE, (HOOKPROC)MouseProc, hInstance, NULL );
807         if (!hMouseHook){
808                 DBW("SetWindowsHookEx error: %d", GetLastError());
809                 return false;
810         }
811
812 //      hKeyHook = SetWindowsHookEx( WH_KEYBOARD, (HOOKPROC)KeyboardProc, hDll, NULL );
813
814         Initialized = true;
815
816 #if GUARD
817         PROTECT_SHARE();
818         DBW("%08X(%08X) Protected", (((INT_PTR)&ExtTextOutAHook) / siPageSize) * siPageSize,&ExtTextOutAHook);
819 #endif
820
821         idDokopopProcess = GetCurrentProcessId();
822
823         // get AMODI infomation.
824         if (!tryAMODI){
825                 tryAMODI = true;
826                 hwndAMODI = FindAMODI();
827 #if 0
828                 if (hwndAMODI){
829                         DWORD procId;
830                         if (GetWindowThreadProcessId(hwnd, &procId)){
831                                 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ, FALSE, procId);
832                                 if (hProc){
833                                         memset(AMODIPath, 0, sizeof(AMODIPath));
834                                         if (GetModuleFileNameEx(hProc, NULL, AMODIPath, sizeof(AMODIPath))>0){
835                                                 // OK
836                                         }
837                                         CloseHandle(hProc);
838                                 }
839                         }
840                 }
841 #endif
842         }
843
844         return true;
845 }
846
847 __declspec(dllexport)
848 void WINAPI Uninit()
849 {
850         UNPROTECT_SHARE();
851         if ( !Initialized ) return;
852
853         DBW("Uninit");
854         UnhookWindowsHookEx( hMouseHook );
855
856 //      UnhookWindowsHookEx( hKeyHook );
857
858 #if USE_VXD
859         UnloadVxD();
860 #endif
861
862         Initialized = false;
863 }
864 __declspec(dllexport)
865 int WINAPI Config( int clickonly, int keyaction, int keyflag )
866 {
867         DBW("Config:%d %d %d", clickonly, keyaction, keyflag);
868         if (clickonly!=-1)
869                 ClickOnlyEnabled = int_bool(clickonly);
870         if ( keyflag != 0 ){
871                 for ( int i=0;KeyConfig[i].Action;i++ ){
872                         if (KeyConfig[i].Action == keyaction){
873                                 KeyConfig[i].Flag = keyflag;
874                                 break;
875                         }
876                 }
877         }
878         return 0;
879 }
880 __declspec(dllexport)
881 int WINAPI Config2( const struct TDCHConfig *cfg )
882 {
883         DBW("Config2: %d %d", cfg->ScaleX, cfg->ScaleY);
884
885         MoveSend = cfg->MoveSend ? true : false;
886         MoveSent = false;
887         OnlyImage = cfg->OnlyImage;
888         ScaleX = cfg->ScaleX;
889         ScaleY = cfg->ScaleY;
890
891         if (cfg->UseAMODI){
892                 if (!ExtAMODI){
893                         if (!hwndAMODI)
894                                 hwndAMODI = FindAMODI();
895                 }
896         } else {
897                 hwndAMODI = NULL;
898                 ExtAMODI = false;
899                 return 0;
900         }
901
902         OnlyAMODI = int_bool(cfg->OnlyAMODI);
903         AMODIPath[0] = '\0';
904         ExtAMODI = false;
905         if (cfg->AMODIPath[0]){
906                 size_t len = strlen(cfg->AMODIPath);
907                 if (len<sizeof(AMODIPath)-2){
908                         memcpy(AMODIPath, cfg->AMODIPath, len);
909                         if (AMODIPath[len-1]!='\\'){
910                                 AMODIPath[len] = '\\';
911                                 len++;
912                         }
913                         AMODIPath[len] = '\0';
914                         ExtAMODI = true;
915                 }
916         }
917         dbw("Config2[%d]: %d %d %s", ++generation, cfg->ScaleX, cfg->ScaleY, AMODIPath);
918         return 0;
919 }
920 //Note:
921 //      non_block = true\82Ì\8fê\8d\87
922 //              \81Ewait\8fó\91Ô\82É\82 \82é\82©\82Ç\82¤\82©\82Í\81AWaitForCaptureResult( false, 0 ) < 0 \82Å\82í\82©\82é\81B
923 //              \81E\95K\82¸\8dÅ\8cã\82É\82ÍWaitForCaptureResult(1,...)\82ð\8cÄ\82Ñ\8fo\82·\82±\82Æ\81B
924 __declspec(dllexport)
925 int WINAPI Capture( HWND hwnd, POINT *ppt, bool movesend, bool non_block )
926 {
927         DBW("Capture:%08X %d,%d %d %d", hwnd, ppt ? ppt->x : 0, ppt ? ppt->y : 0, movesend, non_block);
928         if (!hwnd)
929                 hwnd = hwndLast;
930         POINT pt;
931         if (ppt)
932                 pt = *ppt;
933         else
934                 pt = PrevCursorPoint;
935         const bool image_only = true;
936         const bool runOnLaunchedProc = false;
937         return int_bool(DoCapture(hwnd, pt, movesend, image_only, runOnLaunchedProc, non_block));
938 }
939 //Note:
940 // waittime\82ÍCapture()\8aJ\8en\82µ\82Ä\82©\82ç\82Ì\8co\89ß\8e\9e\8aÔ
941 // polling\82·\82é\8fê\8d\87\82Íwaittime\82ð\8f­\82µ\82¸\82Â\91\9d\82â\82·\95K\97v\82 \82è(\82»\82Ì\8fê\8d\87\82Ísend_text=0)
942 // CaptureImage\82ð\8ds\82Á\82½\8fê\8d\87\82Í\81A\81u\95K\82¸\81vWaitForCaptureResult( 1, ... )\82ð\8cÄ\82Ñ\8fo\82·\95K\97v\82ª\82 \82é\81B
943 // \82»\82¤\82µ\82È\82¢\82Æ\81ACaptureImageBlocking\82ª true \82É\82È\82Á\82½\82Ü\82Ü\81B
944 //
945 // return:
946 //      0 : wait\92\86\82Ì\82à\82Ì\82Í\82È\82µ
947 //      1 : OK(text ready)
948 //      -1: timeout
949 __declspec(dllexport)
950 int WINAPI WaitForCaptureResult( bool send_text, unsigned waittime )
951 {
952         DBW("WaitForCaptureResult: %d %d %d", send_text, waittime, CaptureImageBlocking);
953         if (!CaptureImageBlocking) return 0;
954
955         if (send_text){
956                 if (WaitAndGetResult(ImageTextPath, waittime)){
957                         return 1;
958                 }
959         } else {
960                 HANDLE hf = WaitForResult(ImageTextPath, waittime);
961                 if (hf){
962                         CloseHandle(hf);
963                         return 1;
964                 }
965         }
966         return -1;
967 }
968 #if GUARD
969 void ShareProtect( bool f )
970 {
971         LPVOID BaseAddress = (LPVOID)((((INT_PTR)&ExtTextOutAHook) / siPageSize) * siPageSize);
972
973         DWORD OldProtect;
974         if ( !VirtualProtect( BaseAddress, siPageSize, f ? PAGE_READONLY : PAGE_READWRITE, &OldProtect ) ){
975                 DBW("Cannot change protect:%08X@rehook",BaseAddress);
976         }
977 }
978 #endif
979 DWORD SetWriteProtect( LPVOID addr, bool f )
980 {
981         LPVOID BaseAddress = (LPVOID)((((INT_PTR)addr) / siPageSize) * siPageSize);
982
983         DWORD OldProtect;
984         if ( !VirtualProtect( BaseAddress, siPageSize, f ? PAGE_READONLY : PAGE_READWRITE, &OldProtect ) ){
985                 DBW("Cannot change protect:%08X-%08X@rehook %d", (INT_PTR)BaseAddress>>32, BaseAddress, GetLastError());
986                 return ~0;
987         }
988         return OldProtect;
989 }
990 #if USE_VXD
991 // change write protected memory for Windows9x
992 bool ChangeMemory( void *dst, const void *src, unsigned size )
993 {
994         DWORD DIOC_count;
995         if ( vxd_Handle == INVALID_HANDLE_VALUE ){
996                 if (!LoadVxD())
997                         return false;
998         }
999
1000         bool r = int_bool(DeviceIoControl( vxd_Handle, DIOC_CHANGE_MEMORY, (void*)src, size, dst, 0, &DIOC_count, NULL));
1001 #if USE_DBW
1002         if ( !r ){
1003                 DBW("DeviceIoControl failed");
1004         }
1005 #endif
1006         return r;
1007 }
1008 bool LoadVxD()
1009 {
1010         if (vxd_Handle!=INVALID_HANDLE_VALUE){
1011                 DBW("Already loaded VxD");
1012                 return true;
1013         }
1014         vxd_Handle=CreateFile(&VxDpathName[0],0,0,NULL,0,FILE_FLAG_DELETE_ON_CLOSE,NULL);
1015         return vxd_Handle != INVALID_HANDLE_VALUE;
1016 }
1017 void UnloadVxD()
1018 {
1019         if (vxd_Handle == INVALID_HANDLE_VALUE)
1020                 return;
1021         CloseHandle(vxd_Handle);
1022         vxd_Handle = INVALID_HANDLE_VALUE;
1023 }
1024 #endif
1025 int GetKeyFlag( )
1026 {
1027         int r = 0;
1028         if ( GetKeyState( VK_SHIFT ) & 0x8000 ) r |= KF_SHIFT;
1029         if ( GetKeyState( VK_CONTROL ) & 0x8000 ) r |= KF_CONTROL;
1030         if ( GetKeyState( VK_MENU ) & 0x8000 ) r |= KF_MENU;
1031         if ( GetKeyState( VK_LWIN ) & 0x8000 ) r |= KF_LWIN;
1032         if ( GetKeyState( VK_RWIN ) & 0x8000 ) r |= KF_RWIN;
1033         if ( ClickOnlyEnabled && r == 0 ) r = KF_CLICKONLY;
1034 //      if ( GetKeyState( VK_APPS ) & 0x8000 ) r |= KF_APPS;
1035         return r;
1036 }
1037 LRESULT CALLBACK MouseProc( int code, WPARAM wParam, LPARAM lParam )
1038 {
1039         if ( code < 0 || code != HC_ACTION )
1040                 return CallNextHookEx( hMouseHook, code, wParam, lParam );
1041
1042         MOUSEHOOKSTRUCT *mhs;
1043         HWND hwnd;
1044         int kf;
1045         int i;
1046
1047 #if 0
1048         if (wParam!=0x200 && wParam!=0xA0)
1049                 dbw("WParam:%08X", wParam);
1050 #endif
1051
1052         curProcess = GetCurrentProcessId();
1053         bool runOnLaunchedProc = false;
1054
1055         switch ( wParam ){
1056                 case WM_LBUTTONDOWN:
1057                 // case WM_NCLBUTTONDOWN:
1058                         LButtonDown = true;
1059                         LButtonUpCancel = false;
1060 //                      if (LButtonUpCancel)
1061 //                              goto j_end;
1062                         kf = KF_LEFTCLICK;
1063                         goto j_rbuttondown;
1064                 case WM_MBUTTONDOWN:
1065                 // case WM_NCMBUTTONDOWN:
1066                         MButtonDown = true;
1067                         MButtonUpCancel = false;
1068 //                      if (MButtonUpCancel)
1069 //                              goto j_end;
1070                         kf = KF_MIDCLICK;
1071                         goto j_rbuttondown;
1072                 case WM_RBUTTONDOWN:
1073                 //  case WM_NCRBUTTONDOWN:
1074                         DBW("RButtonDown");
1075                         RButtonUpCancel = false;
1076 //                      if (RButtonUpCancel)
1077 //                              goto j_end;
1078                         kf = 0;
1079                         if (LButtonDown){
1080                                 kf = KF_LRCLICK;
1081                         }
1082         j_rbuttondown:;
1083                         mhs = (MOUSEHOOKSTRUCT*)lParam;
1084                         hwnd = WindowFromPoint( mhs->pt );
1085                         //hwnd = mhs->hwnd;
1086 #if 0
1087                         HWND h = GetParent( hwnd );
1088                         if ( h )
1089                                 hwnd = h;
1090 #endif
1091                         kf |= GetKeyFlag();
1092
1093 #if 0
1094                         dbw("kf=%02X", kf);
1095 #endif
1096
1097                         if (curProcess == idDokopopProcess){
1098                                 // runs on launched process -> ignored.
1099                                 DBW("Runs on launched proc(%d)", curProcess);
1100                                 runOnLaunchedProc = true;
1101                         }
1102
1103                         for ( i=0;KeyConfig[i].Action;i++ ){
1104                                 //DBW("%d:%d %x", i, KeyConfig[i].Action, KeyConfig[i].Flag);
1105                                 if ( kf == KeyConfig[i].Flag ){
1106                                         switch ( KeyConfig[i].Action ){
1107                                                 case KA_POPUP:
1108                                                 case KA_POPUP_NC:
1109                                                         {
1110                                                         const bool move_send = false;
1111                                                         if (DoCapture(hwnd, mhs->pt, move_send, OnlyImage, runOnLaunchedProc)){
1112 j_discard:
1113                                                                 if (wParam == WM_LBUTTONDOWN)
1114                                                                         LButtonUpCancel = true;
1115                                                                 if (wParam == WM_MBUTTONDOWN)
1116                                                                         MButtonUpCancel = true;
1117                                                                 else
1118                                                                         RButtonUpCancel = true;
1119                                                                 return 1;       // discard this message
1120                                                         }
1121                                                         }
1122                                                         break;
1123                                                 case KA_MENU:
1124                                                         DokoPopMenu( hwnd );
1125                                                         goto j_discard;
1126                                                 case KA_TOGGLE:
1127                                                         DBW("KA_TOGGLE");
1128                                                         ToggleClick( hwnd );
1129                                                         goto j_discard;
1130                                         }
1131                                 }
1132                         }
1133                         break;
1134                 case WM_RBUTTONUP:
1135                         DBW("WM_RBUTTONUP:%d",RButtonUpCancel);
1136                         if ( RButtonUpCancel ){
1137                                 RButtonUpCancel = false;
1138                                 return 1;       // no longer process the message
1139                         }
1140                         break;
1141                 case WM_LBUTTONUP:
1142                         LButtonDown = false;
1143                         if ( LButtonUpCancel ){
1144                                 LButtonUpCancel = false;
1145                                 return 1;       // no longer process the message
1146                         }
1147                         break;
1148                 case WM_MBUTTONUP:
1149                         MButtonDown = false;
1150                         if ( MButtonUpCancel ){
1151                                 MButtonUpCancel = false;
1152                                 return 1;       // no longer process the message
1153                         }
1154                         break;
1155                 case WM_MOUSEMOVE:
1156                         if (MoveSend){
1157                                 mhs = (MOUSEHOOKSTRUCT*)lParam;
1158                                 hwnd = WindowFromPoint( mhs->pt );
1159                                 if (PrevCursorPoint.x!=mhs->pt.x || PrevCursorPoint.y!=mhs->pt.y){
1160                                         PrevMoveTime = GetTickCount();
1161                                         MoveSent = false;
1162                                         PrevCursorPoint = mhs->pt;
1163                                         hwndLast = hwnd;
1164                                         //DBW("Moving:%d %d", mhs->pt.x, mhs->pt.y);
1165                                         SendMoveMessage();
1166 #if 0
1167                                         //TODO: 5pixel\96¢\96\9e\82Å\82 \82ê\82ÎDoCapture\82·\82é
1168 #endif
1169                                 } else {
1170                                         if (!MoveSent){
1171 #if 0   // 2014.11.18 inc.srch\82Å\97\8e\82¿\82é\82Ì\82Å\82Æ\82è\82 \82¦\82¸comment out
1172                                                 const int MOVE_SEND_INTERVAL = 50;      // msec
1173                                                 if (GetTickCount()-PrevMoveTime > MOVE_SEND_INTERVAL){
1174                                                         MoveSent = true;
1175                                                         if (DoCapture(hwndLast, PrevCursorPoint, true)){
1176                                                                 // stop the capture from the main.
1177                                                                 SendCancelMove();
1178                                                         }
1179                                                 }
1180 #endif
1181                                         }
1182                                 }
1183                         }
1184                         break;
1185         }
1186
1187 //j_end:;
1188         return CallNextHookEx( hMouseHook, code, wParam, lParam );
1189 }
1190
1191 bool DoCapture(HWND hwnd, POINT pt, bool movesend, bool image_only, bool runOnLaunchedProc, bool non_block)
1192 {
1193         CursorPoint = ScreenPoint = pt;
1194         ScreenToClient( hwnd, &CursorPoint );
1195
1196         if (!image_only && !runOnLaunchedProc){
1197                 //DBW("hwnd:%08X %d %d", (int)hwnd, CursorPoint.x, CursorPoint.y);
1198                 if ((!hwndAMODI && !ExtAMODI) || !OnlyAMODI){
1199                         // Redraw Metafile //
1200                         UNPROTECT_SHARE();
1201                         DBW("Target : %08X %d", hwnd, curProcess);
1202                         bool r = CaptureText( hwnd, movesend );
1203                         PROTECT_SHARE();
1204                         if (r){
1205                                 return true;    // discard this message
1206                         }
1207                 }
1208         }
1209         if (image_only || hwndAMODI || ExtAMODI){
1210                 if (CaptureImage(hwnd, movesend, non_block))
1211                         return true;
1212         }
1213         return false;
1214 }
1215
1216 void CallbackMain(int msg, const void *data, int len, HWND wparam=0)
1217 {
1218         COPYDATASTRUCT cds;
1219         cds.dwData = msg;
1220         cds.cbData = len;
1221         cds.lpData = (LPSTR)data;
1222         SendMessage( hwndCallback, WM_COPYDATA, (WPARAM)wparam, (LPARAM)&cds );
1223 }
1224
1225 void DokoPopMenu( HWND hwnd )
1226 {
1227         CallbackMain(DCH_MENU, NULL, 0, hwnd);
1228 }
1229 void ToggleClick( HWND hwnd )
1230 {
1231         CallbackMain(DCH_TOGGLE, NULL, 0, hwnd);
1232 }
1233 #if 0
1234 LRESULT CALLBACK KeyboardProc( int code, WPARAM wParam, LPARAM lParam )
1235 {
1236         if ( code < 0 || code != HC_ACTION )
1237                 return CallNextHookEx( hKeyHook, code, wParam, lParam );
1238
1239         if ( wParam == VK_CONTROL ){
1240                 if ( lParam & (KF_UP<<16) ){
1241                         // control key up
1242                         // -> hold on time
1243                         goto j1;
1244                 } else
1245                 if ( !(lParam & (KF_REPEAT<<16)) ){
1246                         // control key down and not repeat
1247 //                      DBW("wparam=%08X lparam=%08X",wParam,lParam);
1248                         long nowt = GetTickCount();
1249                         if ( nowt - LastTypeTime < GetDoubleClickTime() ){
1250 //                              DBW("On/off!");
1251                                 ClickOnlyEnabled = !ClickOnlyEnabled;
1252                                 MessageBeep( MB_OK );
1253                                 // -> cancel time
1254                         } else {
1255                                 // -> hold on time
1256                                 LastTypeTime = nowt;
1257                                 goto j1;
1258                         }
1259                 } else {
1260                         // control key down and repeat
1261                         // -> cancel time
1262                 }
1263         }
1264         LastTypeTime -= 10000;
1265 j1:;
1266         return CallNextHookEx( hMouseHook, code, wParam, lParam );
1267 }
1268 #endif
1269
1270 //__declspec(dllexport)
1271 #if HOOK_PAINT || RETRYMETA
1272 HDC WINAPI _BeginPaint( HWND hwnd, LPPAINTSTRUCT ps )
1273 {
1274 //      DBW("BeginPaint");
1275         HDC hdc = ((FNBeginPaint)BeginPaintHook.OrgFunc)( hwnd, ps );
1276         OrgHDC = hdc;
1277         ps->hdc = hdcMeta;
1278 #if 1
1279         ps->rcPaint.left = 0;
1280         ps->rcPaint.top = 0;
1281         ps->rcPaint.right = rcInvalid.right;
1282         ps->rcPaint.bottom = rcInvalid.bottom;
1283 #endif
1284         return hdcMeta;
1285 }
1286 //__declspec(dllexport)
1287 BOOL WINAPI _EndPaint( HWND hwnd, CONST PAINTSTRUCT *ps )
1288 {
1289         ((PAINTSTRUCT*)ps)->hdc = OrgHDC;
1290         return ((FNEndPaint)EndPaintHook.OrgFunc)( hwnd, ps );
1291 }
1292 #endif
1293 #if HOOK_GETDC
1294 HDC WINAPI _GetDC( HWND hwnd )
1295 {
1296         DBW("GetDC");
1297         HDC hdc = ((FNGetDC)GetDCHook.OrgFunc)( hwnd );
1298         OrgHDC = hdc;
1299         if ( hwnd == hwndOrg ){
1300                 return hdcMeta;
1301         } else {
1302                 return OrgHDC;
1303         }
1304 }
1305 int WINAPI _ReleaseDC( HWND hwnd, HDC hdc )
1306 {
1307         DBW("ReleaseDC");
1308         if ( hdc == hdcMeta ){
1309                 hdc = OrgHDC;
1310         }
1311         int r = ((FNReleaseDC)ReleaseDCHook.OrgFunc)( hwnd, hdc );
1312         return r;
1313 }
1314 #endif
1315
1316 #if METAEXTTEXTOUT
1317 //__declspec(dllexport)
1318 BOOL  WINAPI _ExtTextOutA(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCSTR str, UINT count, CONST INT *dx )
1319 {
1320         DBW("_ExtTextOutA");
1321         POINT pt;
1322         GetCurrentPositionEx(hdc,&pt);
1323
1324         BOOL r = ((FNExtTextOutA)ExtTextOutAHook.OrgFunc)( hdc, x, y, option, rc, str, count, dx );
1325
1326         hdcExtTextOut = hdc;
1327
1328         if ( r
1329 #if USE_META
1330                 && hdcMeta != hdc
1331 #endif
1332                 && count > 0 ){
1333                 RECT _rc;
1334                 if ( rc ){
1335                         _rc.right = rc->right;
1336                         _rc.bottom = rc->bottom;
1337                 } else {
1338                         _rc.right = rcClient.right;
1339                         _rc.bottom = rcClient.bottom;
1340                 }
1341                 if ( GetTextAlign( hdc ) & TA_UPDATECP ){
1342                         _rc.left = pt.x;
1343                         _rc.top = pt.y;
1344                 } else {
1345                         _rc.left = x;
1346                         _rc.top = y;
1347                 }
1348                 if ( RetryPhase ){
1349                         if ( TargetBitBltCount == BitBltCount ){
1350                                 _rc.right += CursorPoint.x;     //*+++ bug \82±\82¤\82µ\82È\82¢\82Æ\95\9d\82ª\82¹\82Ü\82­\82Ähit\82µ\82È\82¢
1351                                 OffsetRect( &_rc, TargetOffset.x, TargetOffset.y );
1352                         } else {
1353                                 return r;
1354                         }
1355                 } else {
1356                         ExtTextOutCount++;
1357                 }
1358 #if ORG_OFFSET  /* fixed 2001.1.14 for IE@win2k */
1359                 POINT vpt;
1360                 POINT wpt;
1361                 GetViewportOrgEx( hdc, &vpt );
1362                 GetWindowOrgEx( hdc, &wpt );
1363                 OffsetRect( &_rc, vpt.x-wpt.x, vpt.y-wpt.y);
1364 #else
1365 #if USE_DBW
1366                 POINT vpt;
1367                 POINT wpt;
1368                 GetViewportOrgEx( hdc, &vpt );
1369                 GetWindowOrgEx( hdc, &wpt );
1370                 if (vpt.x != wpt.x || vpt.y != wpt.y)
1371                         DBW("!!!Org DIFF=%d %d",vpt.x-wpt.x, vpt.y-wpt.y);
1372 #endif
1373 #endif
1374
1375                 // \98A\91±\82µ\82½\83e\83L\83X\83g\82Ì\8fê\8d\87\82Í
1376                 // \98A\8c\8b\82·\82é
1377                 if (LastY == _rc.top && LastX == _rc.left ){
1378                         // \98A\91±\82µ\82½\83e\83L\83X\83g\95`\89æ\81¨\98A\8c\8b
1379                         LastTextA->Cat( str, count );
1380                 } else {
1381                         LastTextA->Set( str, count );
1382                 }
1383                 LastX = _rc.left;
1384                 LastY = _rc.top;
1385
1386                 if ( PtInRect( &_rc, CursorPoint ) )
1387                 {
1388 #if DEBUG_HITTEXT
1389                         char *buf = new char[ count + 1 ];
1390                         CopyMemory( buf, str, count );
1391                         buf[count] = '\0';
1392                         DBW("CheckA -- %d %d %d %d (%d,%d)", _rc.left, _rc.top, _rc.right, _rc.bottom, CursorPoint.x, CursorPoint.y, count);
1393                         DBW("%s", buf);
1394                         delete[] buf;
1395 #endif
1396                         int loc = GetTextFromPoint( hdc, str, count, CursorPoint.x - _rc.left, CursorPoint.y - _rc.top, dx );
1397                         if ( loc != -1 ){
1398                                 FoundLocA = loc + LastTextA->GetLength() - count;
1399                                 FoundTextA->Set( LastTextA );
1400 #if DEBUG_HITTEXT
1401                                 DBW("HitA loc=%d Len=%d Text=%ws", FoundLocA, FoundTextA->GetLength(), FoundTextA->c_str());
1402 #endif
1403                         }
1404                 }
1405         }
1406
1407         return r;
1408 }
1409 //__declspec(dllexport)
1410 BOOL  WINAPI _ExtTextOutW(HDC hdc, int x, int y, UINT option, CONST RECT *rc, LPCWSTR str, UINT count, CONST INT *dx )
1411 {
1412 //      DBW("_ExtTextOutW");
1413         POINT pt;
1414         GetCurrentPositionEx(hdc,&pt);
1415
1416         BOOL r = ((FNExtTextOutW)ExtTextOutWHook.OrgFunc)( hdc, x, y, option, rc, str, count, dx );
1417
1418         hdcExtTextOut = hdc;
1419
1420         if ( r
1421 #if USE_META
1422                 && hdcMeta != hdc
1423 #endif
1424                 && count > 0 ){
1425                 RECT _rc;
1426                 if ( rc ){
1427                         _rc.right = rc->right;
1428                         _rc.bottom = rc->bottom;
1429                 } else {
1430                         _rc.right = rcClient.right;
1431                         _rc.bottom = rcClient.bottom;
1432                 }
1433                 if ( GetTextAlign( hdc ) & TA_UPDATECP ){
1434                         _rc.left = pt.x;
1435                         _rc.top = pt.y;
1436                 } else {
1437                         _rc.left = x;
1438                         _rc.top = y;
1439                 }
1440                 if ( RetryPhase ){
1441                         if ( TargetBitBltCount == BitBltCount ){
1442                                 _rc.right += CursorPoint.x;     //*+++ bug \82±\82¤\82µ\82È\82¢\82Æ\95\9d\82ª\82¹\82Ü\82­\82Ähit\82µ\82È\82¢
1443                                 OffsetRect( &_rc, TargetOffset.x, TargetOffset.y );
1444                         } else {
1445                                 return r;
1446                         }
1447                 } else {
1448                         ExtTextOutCount++;
1449                 }
1450 #if ORG_OFFSET  /* fixed 2001.1.14 for IE@win2k */
1451                 POINT vpt;
1452                 POINT wpt;
1453                 GetViewportOrgEx( hdc, &vpt );
1454                 GetWindowOrgEx( hdc, &wpt );
1455                 OffsetRect( &_rc, vpt.x-wpt.x, vpt.y-wpt.y);
1456 #else   // !ORG_OFFSET
1457 #if USE_DBW
1458                 POINT vpt;
1459                 POINT wpt;
1460                 GetViewportOrgEx( hdc, &vpt );
1461                 GetWindowOrgEx( hdc, &wpt );
1462                 if (vpt.x != wpt.x || vpt.y != wpt.y)
1463                         DBW("!!!Org DIFF=%d %d",vpt.x-wpt.x, vpt.y-wpt.y);
1464 #endif  // USE_DBW
1465 #endif  // !ORG_OFFSET
1466
1467                 // \98A\91±\82µ\82½\83e\83L\83X\83g\82Ì\8fê\8d\87\82Í\98A\8c\8b\82·\82é
1468                 if (LastY == _rc.top && LastX == _rc.left ){
1469                         // \98A\91±\82µ\82½\83e\83L\83X\83g\95`\89æ\81¨\98A\8c\8b
1470                         LastTextW->Cat( str, count );
1471                 } else {
1472                         LastTextW->Set( str, count );
1473                 }
1474                 LastX = _rc.left;
1475                 LastY = _rc.top;
1476
1477                 if ( PtInRect( &_rc, CursorPoint ) )
1478                 {
1479                         DBW("%04X %04X %04X %04X",
1480                                 str[0],
1481                                 str[1],
1482                                 str[2],
1483                                 str[3]);
1484 #if DEBUG_HITTEXT
1485                         wchar_t *buf = new wchar_t[ count + 1 ];
1486                         CopyMemory( buf, str, count*sizeof(wchar_t) );
1487                         buf[count] = '\0';
1488                         DBW("CheckW -- %d %d %d %d (%d,%d)", _rc.left, _rc.top, _rc.right, _rc.bottom, CursorPoint.x, CursorPoint.y, count);
1489                         DBW("%ws", buf);
1490                         delete[] buf;
1491 #endif
1492                         int loc = GetTextFromPoint( hdc, str, count, CursorPoint.x - _rc.left, CursorPoint.y - _rc.top, dx );
1493                         if ( loc != -1 ){
1494                                 FoundLocW = loc + LastTextW->GetLength() - count;
1495                                 FoundTextW->Set( LastTextW );
1496 #if DEBUG_HITTEXT
1497                                 DBW("HitW loc=%d Len=%d Text=%ws", FoundLocW, FoundTextW->GetLength(), FoundTextW->c_str());
1498 #endif
1499                         }
1500                 }
1501         }
1502
1503         return r;
1504 }
1505 #endif  // !METAEXTTEXTOUT
1506
1507 #if HOOK_BITBLT
1508 BOOL WINAPI _BitBlt(HDC hdcdest, int xdest, int ydest, int width, int height, HDC hdcsrc, int xsrc, int ysrc, DWORD rop )
1509 {
1510         DBW("BitBlt:%08X %d %d %d %d <- %08X %d %d", hdcdest, xdest, ydest, width, height, hdcsrc, xsrc, ysrc );
1511         BOOL r = ((FNBitBlt)BitBltHook.OrgFunc)(hdcdest, xdest, ydest, width, height, hdcsrc, xsrc, ysrc, rop );
1512 //      DBW("BitBlt:%08X %d %d %d %d <- %08X %d %d", hdcdest, xdest, ydest, width, height, hdcsrc, xsrc, ysrc );
1513         if ( r && hdcExtTextOut == hdcsrc ){
1514                 if ( !RetryPhase ){
1515                         // \8d¡\89ñ\82ÌBitBlt\8e\9e\82ÉExtTextOut\82ª\82 \82Á\82½\82©\81H
1516                         if ( ExtTextOutCount > 0 ){
1517                                 // CursorPoint\82ª\8aÜ\82Ü\82ê\82é\82©\81H
1518                                 DBW("ExtTextOutCount=%d",ExtTextOutCount);
1519                                 if ( (xdest <= CursorPoint.x)
1520                                         && (xdest+width > CursorPoint.x)
1521                                         && (ydest <= CursorPoint.y)
1522                                         && (ydest+height > CursorPoint.y)
1523                                 ){
1524                                         TargetBitBltCount = BitBltCount;
1525                                         TargetOffset.x = xdest - xsrc;
1526                                         TargetOffset.y = ydest - ysrc;
1527                                         DBW("TargetOffset %d %d (%d,%d %dx%d)<-(%d,%d)",
1528                                                 TargetOffset.x, TargetOffset.y,xdest,ydest,width,height,xsrc,ysrc);
1529 #if USE_DBW
1530                                         {
1531                                         POINT vpt;
1532                                         POINT wpt;
1533                                         GetViewportOrgEx( hdcdest, &vpt );
1534                                         GetWindowOrgEx( hdcdest, &wpt );
1535                                         DBW("BitBlt OrgDIFF=%d %d",vpt.x-wpt.x, vpt.y-wpt.y);
1536                                         SIZE sz1;
1537                                         SIZE sz2;
1538                                         GetViewportExtEx( hdcdest, &sz1 );
1539                                         GetWindowExtEx( hdcdest, &sz2 );
1540                                         DBW("BitBlt Ext %d (%d,%d) (%d,%d)", GetMapMode(hdcdest), sz1.cx, sz1.cy, sz2.cx, sz2.cy );
1541 #if 1
1542                                         XFORM xform;
1543                                         GetWorldTransform( hdcdest, &xform );
1544                                         {
1545                                         char buf[100];
1546                                         sprintf(buf,"== [%d] %g %g %g %g %g %g", GetGraphicsMode(hdcdest), xform.eM11, xform.eM12, xform.eM21, xform.eM22, xform.eDx, xform.eDy);
1547                                         DBW(buf);
1548                                         }
1549 #endif
1550                                         }
1551 #endif
1552                                 }
1553 #if METAEXTTEXTOUT
1554                                 if ( TargetBitBltCount != -1 ){
1555                                         // \82·\82Å\82É\82Ù\82©\82Ìband\82Åhit\82µ\82Ä\82¢\82é\8fê\8d\87\81A
1556                                         // Cancel ExtTextOut
1557                                         FoundLocA = -1;
1558                                         FoundLocW = -1;
1559                                 }
1560 #endif
1561                         }
1562                 }
1563                 BitBltCount++;
1564                 DBW("BitBltCount=%d",BitBltCount);
1565                 ExtTextOutCount = 0;
1566                 return r;
1567         } else {
1568 //              DBW("Unknown destination BitBlt %08X(%d,%d %dx%d)<-%08X(%d,%d)",hdcdest,xdest,ydest,width,height,hdcsrc,xsrc,ysrc);
1569         }
1570         return r;
1571 }
1572 #endif
1573
1574 #if HOOK_TEXT
1575 #define HK1( name, ret_type, args ) \
1576         ret_type r = ((FN##name)name##Hook.OrgFunc) args; \
1577         return r
1578 LONG WINAPI _TabbedTextOutA( HDC hdc, int x, int y, LPCSTR str, int count, int ntabs, LPINT tabs, int origin )
1579 {
1580         DBW("_TabbedTextOutA");
1581         HK1( TabbedTextOutA, LONG, ( hdc, x, y, str, count, ntabs, tabs, origin ) );
1582 }
1583 LONG WINAPI _TabbedTextOutW( HDC hdc, int x, int y, LPCWSTR str, int count, int ntabs, LPINT tabs, int origin )
1584 {
1585         DBW("TabbedTextOutW");
1586         HK1( TabbedTextOutW, LONG, ( hdc, x, y, str, count, ntabs, tabs, origin ) );
1587 }
1588 BOOL WINAPI _TextOutA( HDC hdc, int x, int y, LPCSTR str, int count )
1589 {
1590         DBW("_TextOutA");
1591         HK1( TextOutA, BOOL, ( hdc, x, y, str, count ) );
1592 }
1593 BOOL WINAPI _TextOutW( HDC hdc, int x, int y, LPCWSTR str, int count )
1594 {
1595         DBW("_TextOutW");
1596         HK1( TextOutW, BOOL, ( hdc, x, y, str, count ) );
1597 }
1598 int WINAPI _DrawTextA( HDC hdc, LPCSTR str, int count, LPRECT rc, UINT format )
1599 {
1600         DBW("s5");
1601         HK1( DrawTextA, int, ( hdc, str, count, rc, format ) );
1602 }
1603 int WINAPI _DrawTextW( HDC hdc, LPCWSTR str, int count, LPRECT rc, UINT format )
1604 {
1605         DBW("s6");
1606         HK1( DrawTextW, int, ( hdc, str, count, rc, format ) );
1607 }
1608 int WINAPI _DrawTextExA( HDC hdc, LPCSTR str, int count, LPRECT rc, UINT format, LPDRAWTEXTPARAMS params )
1609 {
1610         DBW("s7");
1611         HK1( DrawTextExA, int, ( hdc, str, count, rc, format, params ) );
1612 }
1613 int WINAPI _DrawTextExW( HDC hdc, LPCWSTR str, int count, LPRECT rc, UINT format, LPDRAWTEXTPARAMS params )
1614 {
1615         DBW("s8");
1616         HK1( DrawTextExW, int, ( hdc, str, count, rc, format, params ) );
1617 }
1618 #endif  // HOOK_TEXT
1619
1620 bool CaptureText( HWND hwnd, bool movesend )
1621 {
1622         if ( !hwnd ){
1623                 return false;
1624         }
1625
1626         MoveSendMode = movesend;
1627
1628         //DoScale(NULL, &CursorPoint, 1);
1629
1630 #if METAEXTTEXTOUT
1631         FoundLocA = -1;
1632         FoundLocW = -1;
1633         FoundTextA = new TString<char>;
1634         FoundTextW = new TString<wchar_t>;
1635         LastTextA = new TString<char>;
1636         LastTextW = new TString<wchar_t>;
1637 #endif
1638
1639 #if !USE_REDRAW
1640         HRGN hRgn;
1641 #endif
1642
1643         GetClientRect( hwnd, &rcClient );
1644         GetUpdateRect( hwnd, &rcOrgInvalid, FALSE );
1645
1646 #if USE_OPTIMALINVALID
1647         SetRect( &rcInvalid, 0, max(CursorPoint.y - 64,0), rcClient.right, max(CursorPoint.y + 64,0) );
1648 #else
1649         rcInvalid = rcClient;
1650 #endif
1651
1652 #if !USE_REDRAW
1653         hRgn = CreateRectRgn( rcInvalid.left, rcInvalid.top, rcInvalid.right, rcInvalid.bottom );
1654
1655 #if USE_INVALIDATE
1656         InvalidateRect( hwnd, &rcInvalid, INVALIDATE_TRUE );
1657 #endif
1658
1659         SendMessage( hwnd, WM_PAINT, 0, 0 );
1660         SendMessage( hwnd, WM_NCPAINT, (WPARAM)hRgn, 0 );
1661 #endif
1662
1663         hwndOrg = hwnd;
1664
1665 #if USE_META
1666         HDC hdc;
1667 #endif
1668
1669         HINSTANCE hPSAPI = NULL;
1670         HMODULE hInst;
1671         HMODULE hInstGdi;
1672
1673         hInst = GetModuleHandleA( STR_KERNEL32 );
1674         fnCreateToolhelp32Snapshot = (FNCreateToolhelp32Snapshot)GetProcAddress( hInst, STR_CreateToolhelp32Snapshot );
1675         if (fnCreateToolhelp32Snapshot){
1676                 // Toolhelp\82É\82æ\82émodule enumration\82ª\8eg\97p\89Â\94\
1677                 fnModule32First = (FNModule32First)GetProcAddress( hInst, STR_Module32First );
1678                 fnModule32Next = (FNModule32Next)GetProcAddress( hInst, STR_Module32Next );
1679         } else {
1680                 // Toolhelp\82ª\91\8dÝ\82µ\82È\82¢\8fê\8d\87
1681                 hPSAPI = LoadLibrary( STR_PSAPI );
1682                 DBW("LoadLibrary : %08X",hPSAPI);
1683                 if (!hPSAPI){
1684                         DBW("Cannot load PSAPI.DLL!!");
1685                         return false;
1686                 }
1687                 fnEnumProcessModules = (FNEnumProcessModules)GetProcAddress( hPSAPI, STR_EnumProcessModules );
1688                 fnGetModuleFileNameExA = (FNGetModuleFileNameExA)GetProcAddress( hPSAPI, STR_GetModuleFileNameExA );
1689         }
1690
1691         hInst = GetModuleHandleA( STR_USER32 );
1692 #if USE_DBW
1693         if ( !hInst ){
1694                 DBW("Cannot load USER32.DLL");
1695                 return false;
1696         }
1697 #endif
1698         hInstGdi = GetModuleHandleA( STR_GDI32 );
1699 #if USE_DBW
1700         if ( !hInstGdi ){
1701                 DBW("Cannot load GDI32.DLL");
1702                 goto err9;
1703         }
1704 #endif
1705
1706 #if METAEXTTEXTOUT
1707         if ( !ExtTextOutAHook.GetProcOrgFunc( hInstGdi ) ){
1708                 DBW("Cannot find ExtTextOutA");
1709                 goto err8;
1710         }
1711         if ( !ExtTextOutWHook.GetProcOrgFunc( hInstGdi ) ){
1712                 DBW("Cannot find ExtTextOutW");
1713                 goto err7;
1714         }
1715 #endif
1716
1717 #if HOOK_BITBLT
1718         if ( !BitBltHook.GetProcOrgFunc( hInstGdi ) ){
1719                 DBW("Cannot find BitBlt");
1720                 goto err71;
1721         }
1722 #endif
1723         RetryPhase = false;
1724         TargetBitBltCount = -1;
1725         BitBltCount = 0;
1726         ExtTextOutCount = 0;
1727
1728 #if HOOK_PAINT
1729         if ( !BeginPaintHook.GetProcOrgFunc( hInst ) ){
1730                 DBW("Cannot hook BeginPaint");
1731                 goto err73;
1732         }
1733         if ( !EndPaintHook.GetProcOrgFunc( hInst ) ){
1734                 DBW("Cannot hook EndPaint");
1735                 goto err6;
1736         }
1737 #endif
1738
1739 #if HOOK_TEXT
1740         TabbedTextOutAHook.GetProcOrgFunc( hInst );
1741         TabbedTextOutWHook.GetProcOrgFunc( hInst );
1742         TextOutAHook.GetProcOrgFunc( hInstGdi );
1743         TextOutWHook.GetProcOrgFunc( hInstGdi );
1744         DrawTextAHook.GetProcOrgFunc( hInst );
1745         DrawTextWHook.GetProcOrgFunc( hInst );
1746         DrawTextExAHook.GetProcOrgFunc( hInst );
1747         DrawTextExWHook.GetProcOrgFunc( hInst );
1748 #endif
1749
1750 #if USE_META
1751         hdc = GetDC( hwnd );
1752         if ( !hdc ){
1753                 DBW("Cannot get DC");
1754                 goto err5;
1755         }
1756 #endif
1757
1758 #if HOOK_GETDC
1759         if ( !GetDCHook.GetProcOrgFunc( hInst ) ){
1760                 DBW("Cannot hook GetDC");
1761                 goto err4;
1762         }
1763         if ( !ReleaseDCHook.GetProcOrgFunc( hInst ) ){
1764                 DBW("Cannot hook ReleaseDC");
1765                 goto err3;
1766         }
1767 #endif
1768
1769         {
1770         DBW("Hooked successfully");
1771 //              rect.right = 9999;
1772 //              rect.bottom = 9999;
1773 #if 0
1774                 int iWidthMM = GetDeviceCaps(hdc, HORZSIZE);
1775                 int iHeightMM = GetDeviceCaps(hdc, VERTSIZE);
1776                 int iWidthPels = GetDeviceCaps(hdc, HORZRES);
1777                 int iHeightPels = GetDeviceCaps(hdc, VERTRES);
1778
1779                 // Use iWidthMM, iWidthPels, iHeightMM, and iHeightPels to determine the
1780                 // number of .01-millimeter units per pixel in the x and y directions.
1781
1782                 int iMMPerPelX = (iWidthMM * 100)/iWidthPels;
1783                 int iMMPerPelY = (iHeightMM * 100)/iHeightPels;
1784                 DBW("-%d %d-",iMMPerPelX, iMMPerPelY);
1785
1786                 // Convert client coordinates to .01-mm units.
1787
1788                 rcClient.left = rcClient.left * iMMPerPelX;
1789                 rcClient.top = rcClient.top * iMMPerPelY;
1790                 rcClient.right = rcClient.right * iMMPerPelX;
1791                 rcClient.bottom = rcClient.bottom * iMMPerPelY;
1792 #endif
1793
1794 #if USE_META
1795                 hdcMeta = CreateEnhMetaFile(hdc,
1796                                   NULL,
1797                                   &rcClient, "DCHook\0EnhMetaFile\0");
1798                 if ( !hdcMeta ){
1799                         DBW("Cannot create Meta file");
1800                         goto err3;
1801                 }
1802
1803                 DBW("hdcMeta=%08X", hdcMeta);
1804 #endif
1805
1806 #if USE_REDRAW
1807                 RedrawWindow( hwnd, &rcInvalid, NULL, RDW_UPDATENOW | RDW_NOERASE | RDW_NOFRAME | RDW_INVALIDATE );
1808 #else
1809                 WNDPROC PaintWndProc = (WNDPROC)GetWindowLong( hwnd, GWL_WNDPROC );
1810                 SendMessage( hwnd, WM_PAINT, (WPARAM)hdcMeta, 0 );
1811 #endif
1812 #if HOOK_GETDC
1813                 ReleaseDCHook.Finish();
1814                 GetDCHook.Finish();
1815 #endif
1816
1817 #if HOOK_TEXT
1818                 TabbedTextOutAHook.Finish( );
1819                 TabbedTextOutWHook.Finish( );
1820                 TextOutAHook.Finish( );
1821                 TextOutWHook.Finish( );
1822                 DrawTextAHook.Finish( );
1823                 DrawTextWHook.Finish( );
1824                 DrawTextExAHook.Finish( );
1825                 DrawTextExWHook.Finish( );
1826 #endif
1827
1828 #if HOOK_PAINT
1829                 EndPaintHook.Finish();
1830                 BeginPaintHook.Finish();
1831 #endif
1832
1833 #if HOOK_BITBLT
1834                 BitBltHook.Finish();
1835 #endif
1836
1837 #if METAEXTTEXTOUT
1838                 ExtTextOutAHook.Finish();
1839                 ExtTextOutWHook.Finish();
1840 #endif
1841
1842                 // Notify start enumrate meta-file
1843                 CallbackMain(DCH_START, &CursorPoint, sizeof(CursorPoint), hwnd);
1844
1845                 HitFound = false;
1846
1847 #if USE_META
1848                 HENHMETAFILE emf = CloseEnhMetaFile( hdcMeta );
1849
1850                 if ( emf )
1851 #endif
1852                 {
1853 #if METAEXTTEXTOUT
1854                         if ( FoundLocA != -1 || FoundLocW != -1 ){
1855 //                              DBW("Hit ExtText:%d %d",FoundLocA,FoundLocW);
1856                                 // ExtTextOutx hook\82Ì\82Ù\82¤\82ð\97D\90æ\82·\82é
1857                                 ExtTextOutHit( );
1858                                 HitFound = true;
1859                         } else
1860 #endif
1861                         {
1862 #if USE_META
1863                                 // Create compatible device-context for enumration
1864                                 HDC _hdc = CreateCompatibleDC( hdc );
1865                                 HBITMAP hbitmap = CreateCompatibleBitmap( hdc, rcClient.right, rcClient.bottom );
1866                                 HGDIOBJ gdiobj = SelectObject( _hdc, hbitmap );
1867
1868                                 DBW("Start meta");
1869                                 // Enumerate meta-file
1870                                 EnumEnhMetaFile( _hdc, emf, EnumMetaFileProc, NULL, &rcClient );
1871                                 DBW("End meta");
1872
1873                                 // Delete compatible device-context
1874                                 SelectObject( _hdc, gdiobj );
1875                                 DeleteObject( hbitmap );
1876                                 DeleteDC( _hdc );
1877 #endif
1878                         }
1879 #if USE_META
1880                         DeleteEnhMetaFile( emf );
1881 #endif
1882                 }
1883 #if USE_META
1884                 else {
1885                         DBW("emf is NULL");
1886                 }
1887 #endif
1888
1889 #if METAEXTTEXTOUT
1890                 if ( !HitFound && TargetBitBltCount != -1 ){
1891                         DBW("Search from band:%d",TargetBitBltCount);
1892 #if USE_META
1893                         // Band\82©\82ç\8c\9f\8dõ
1894                         hdcMeta = CreateCompatibleDC( hdc );
1895                         if ( !hdcMeta ){
1896                                 DBW("Cannot create HDC in retry");
1897                         } else
1898 #endif
1899                         {
1900 #if USE_META
1901                                 HBITMAP hbitmap = CreateCompatibleBitmap( hdc, rcClient.right, rcClient.bottom );
1902                                 HGDIOBJ gdiobj = SelectObject( hdcMeta, hbitmap );
1903                                 DBW("hdcMeata=%08X", hdcMeta);
1904 #endif
1905
1906                                 BitBltCount = 0;
1907                                 RetryPhase = true;
1908 #if METAEXTTEXOUT
1909                                 FoundLocA = -1;
1910                                 FoundLocW = -1;
1911 #endif
1912
1913 #if METAEXTTEXTOUT
1914                                 ExtTextOutAHook.HookAgain();
1915                                 ExtTextOutWHook.HookAgain();
1916 #endif
1917 #if HOOK_BITBLT
1918                                 BitBltHook.HookAgain();
1919 #endif
1920 #if HOOK_PAINT
1921                                 BeginPaintHook.HookAgain();
1922                                 EndPaintHook.HookAgain();
1923 #endif
1924
1925 //                              DBW("t1:%d %d %d %d",rcClient.left, rcClient.top,rcClient.right,rcClient.bottom);
1926
1927 #if USE_INVALIDATE
1928                                 InvalidateRect( hwnd, &rcInvalid, INVALIDATE_TRUE );
1929 #endif
1930
1931 #if USE_REDRAW
1932                                 RedrawWindow( hwnd, &rcInvalid, NULL, RDW_UPDATENOW | RDW_NOERASE | RDW_NOFRAME | RDW_INVALIDATE );
1933 #else
1934                                 CallWindowProc( (WNDPROC)PaintWndProc, hwnd, WM_PAINT, (WPARAM)hdcMeta, 0 );
1935 #endif
1936
1937 #if HOOK_PAINT
1938                                 EndPaintHook.Finish();
1939                                 BeginPaintHook.Finish();
1940 #endif
1941 #if HOOK_BITBLT
1942                                 BitBltHook.Finish();
1943 #endif
1944
1945 #if METAEXTTEXTOUT
1946                                 ExtTextOutAHook.Finish();
1947                                 ExtTextOutWHook.Finish();
1948 #endif
1949 #if USE_META
1950                                 SelectObject( hdcMeta, gdiobj );
1951                                 DeleteObject( hbitmap );
1952                                 DeleteDC( hdcMeta );
1953 #endif
1954                                 if ( FoundLocA != -1 || FoundLocW != -1 ){
1955                                         DBW("Found in BitBlt ExtText:%d %d",FoundLocA,FoundLocW);
1956                                         ExtTextOutHit( );
1957                                         HitFound = true;
1958                                 }
1959                         }
1960                 }
1961 #endif  // METAEXTTEXTOUT
1962
1963 #if RETRYMETA
1964                 if ( !HitFound ){
1965                         HENHMETAFILE emf;
1966 #if !USE_META
1967                         HDC hdc = GetDC( hwnd );
1968                         if ( !hdc ){
1969                                 DBW("Cannot get DC");
1970                                 goto err01;
1971                         }
1972 #endif
1973 #if HOOK_PAINT
1974                         if ( !BeginPaintHook.HookAgain( ) ){
1975                                 DBW("Cannot hook BeginPaint");
1976                                 goto err02;
1977                         }
1978                         if ( !EndPaintHook.HookAgain( ) ){
1979                                 DBW("Cannot hook EndPaint");
1980                                 goto err03;
1981                         }
1982 #else
1983                         if ( !BeginPaintHook.GetProcOrgFunc( hInst ) ){
1984                                 DBW("Cannot hook BeginPaint");
1985                                 goto err02;
1986                         }
1987                         if ( !EndPaintHook.GetProcOrgFunc( hInst ) ){
1988                                 DBW("Cannot hook EndPaint");
1989                                 goto err03;
1990                         }
1991 #endif
1992
1993                         hdcMeta = CreateEnhMetaFile(hdc,
1994                                           NULL,
1995                                           &rcClient, _T("DCHook\0EnhMetaFile\0"));
1996                         if ( !hdcMeta ){
1997                                 DBW("Cannot create Meta file");
1998                                 goto err04;
1999                         }
2000                         DBW("hdcMeta=%08X", hdcMeta);
2001 //                      InvalidateRect( hwnd, &rcInvalid, INVALIDATE_TRUE );
2002 #if 1           // 2000.7.15 NT\82Å\82à\82È\82º\82±\82Á\82¿\82É\82µ\82Ä\82¢\82È\82©\82Á\82½\82Ì\82©\82í\82©\82ç\82È\82¢\82ª\81E\81E\81E
2003                         SendMessage( hwnd, WM_PAINT, (WPARAM)hdcMeta, 0 );
2004 #else
2005                         // Notepad\82Å\82Í\88Ù\8fí\8fI\97¹\82·\82é\82½\82ß\8bp\89º
2006                         // \89½\82à\82È\82¢\82Æ\82±\82ë\82ÅCtrl+\89E\83N\83\8a\83b\83N
2007                         WNDPROC PaintWndProc = (WNDPROC)GetWindowLong( hwnd, GWL_WNDPROC );
2008                         if ( PaintWndProc ){
2009                                 PaintWndProc( hwnd, WM_PAINT, (WPARAM)hdcMeta, 0 );
2010                         }
2011 #endif
2012                         EndPaintHook.Finish();
2013                         BeginPaintHook.Finish();
2014
2015                         emf = CloseEnhMetaFile( hdcMeta );
2016
2017                         if ( emf ){
2018                                 HDC _hdc = CreateCompatibleDC( hdc );
2019                                 HBITMAP hbitmap = CreateCompatibleBitmap( hdc, rcClient.right, rcClient.bottom );
2020                                 HGDIOBJ gdiobj = SelectObject( _hdc, hbitmap );
2021
2022                                 DBW("Start meta-retry");
2023                                 // Enumerate meta-file
2024                                 EnumEnhMetaFile( _hdc, emf, EnumMetaFileProc, NULL, &rcClient );
2025                                 DBW("End meta-retry");
2026
2027                                 // Delete compatible device-context
2028                                 SelectObject( _hdc, gdiobj );
2029                                 DeleteObject( hbitmap );
2030                                 DeleteDC( _hdc );
2031                                 DeleteEnhMetaFile( emf );
2032                         }
2033                 err04:
2034                         EndPaintHook.Finish();
2035                 err03:
2036                         BeginPaintHook.Finish();
2037                 err02:
2038 #if !USE_META
2039                         ReleaseDC( hwnd, hdc );
2040 #endif
2041                 err01:;
2042                 }
2043 #endif
2044                 
2045                 // Notify end enumrate meta-file
2046                 CallbackMain(DCH_END | (MoveSendMode ? DCH_MOVESEND : 0), NULL, 0, hwnd);
2047         }
2048
2049 #if USE_META
2050         ReleaseDC( hwnd, hdc );
2051 #endif
2052
2053         if ( rcOrgInvalid.right != 0 ){
2054                 DBW("Update OrgInvalid--------");
2055                 InvalidateRect( hwnd, NULL, INVALIDATE_TRUE );
2056         }
2057
2058         goto jreturn;
2059
2060 #if HOOK_GETDC || USE_META
2061 err3:;
2062 #endif
2063 #if HOOK_GETDC
2064         GetDCHook.Finish();
2065 err4:;
2066 #if USE_META
2067         ReleaseDC( hwnd, hdc );
2068 #endif
2069 #endif
2070 #if USE_META
2071 err5:;
2072 #endif
2073 #if HOOK_PAINT
2074         EndPaintHook.Finish();
2075 err6:;
2076         BeginPaintHook.Finish();
2077 err73:;
2078 #endif
2079 #if HOOK_BITBLT
2080         BitBltHook.Finish();
2081 #endif
2082 #if HOOK_BITBLT
2083 err71:;
2084 #endif
2085 #if METAEXTTEXTOUT
2086         ExtTextOutWHook.Finish();
2087 err7:;
2088         ExtTextOutAHook.Finish();
2089 err8:
2090 #endif
2091         if (hPSAPI)
2092                 FreeLibrary( hPSAPI );
2093 #if USE_DBW
2094 err9:
2095 #endif
2096         HitFound = false;
2097 jreturn:;
2098 #if USE_VXD
2099         if (vxd_Handle!=INVALID_HANDLE_VALUE)
2100                 UnloadVxD();
2101 #endif
2102 #if METAEXTTEXTOUT
2103         delete FoundTextA;
2104         delete FoundTextW;
2105         delete LastTextA;
2106         delete LastTextW;
2107 #endif
2108
2109         return HitFound;
2110 }
2111 #if METAEXTTEXTOUT
2112 void ExtTextOutHit()
2113 {
2114         if ( FoundLocA != -1 ){
2115                 // Hit on ANSI
2116                 DBW("Hit on ANSI@ExtTextOut");
2117                 CallbackMain(DCH_HITTEXT1, FoundTextA->c_str(), FoundTextA->GetByte(), (HWND)FoundLocA);
2118         } else {
2119                 // Hit on UNICODE
2120                 DBW("Hit on UNICODE@ExtTextOut");
2121                 CallbackMain(DCH_HITTEXT2, FoundTextW->c_str(), FoundTextW->GetByte(), (HWND)FoundLocW);
2122         }
2123 }
2124 #endif  // METAEXTTEXTOUT
2125
2126 void DoScale(HDC hdc, POINT *pts, int num)
2127 {
2128         //TODO: hInst, proc\82Íglobal\82É\82µ\82½\82Ù\82¤\82ª\82¢\82¢\82Ì\82Å\82Í\81H
2129
2130         int scale = 0;
2131         if (ScaleX && ScaleY){
2132                 scale = ScaleX; // \8ew\92è\82µ\82½scaling parameter
2133         } else {
2134                 scale = GetMonitorScale();
2135                 if (scale == 96) return;
2136         }
2137
2138 #if 1
2139 #if 1
2140         PROCESS_DPI_AWARENESS value = Process_DPI_Unaware;
2141         if (hInstSHCore){
2142                 if (!GetProcessDPIAwareness){
2143                         GetProcessDPIAwareness = (FNGetProcessDPIAwareness)GetProcAddress(hInstSHCore, "GetProcessDpiAwareness");
2144                 }
2145                 if (GetProcessDPIAwareness){
2146                         GetProcessDPIAwareness(hProcess, &value);
2147                         DBW("DPIAware: value=%d", value);
2148                 }
2149         }
2150         if (value != Process_System_DPI_Aware){
2151                 int dpi_x = scale;
2152                 int dpi_y = scale;
2153                 DBW("dpi: %d,%d", dpi_x, dpi_y);
2154                 for (int i=0;i<num;i++){
2155                         pts[i].x = MulDiv(pts[i].x, dpi_x, 96);
2156                         pts[i].y = MulDiv(pts[i].y, dpi_y, 96);
2157                 }
2158         }
2159 #else
2160         HINSTANCE hInst = NULL;
2161         FNGetProcessDPIAwareness GetProcessDPIAwareness = NULL;
2162         //FNSetProcessDPIAwareness SetProcessDPIAwareness = NULL;
2163         //if (!GetProcessDPIAwareness)
2164         {
2165                 hInst = LoadLibrary("shcore.dll");
2166                 if (hInst){
2167                         GetProcessDPIAwareness = (FNGetProcessDPIAwareness)GetProcAddress(hInst, "GetProcessDpiAwareness");
2168                         //SetProcessDPIAwareness = (FNSetProcessDPIAwareness)GetProcAddress(hInst, "SetProcessDpiAwareness");
2169                         //DBW("DPI API:%08X %08X", GetProcessDPIAwareness, SetProcessDPIAwareness);
2170                         DBW("DPI API:%08X", GetProcessDPIAwareness);
2171                 }
2172         }
2173         if (GetProcessDPIAwareness || (ScaleX && ScaleY)){
2174                 int dpi_x, dpi_y;
2175                 PROCESS_DPI_AWARENESS value;
2176                 if (GetProcessDPIAwareness && hdc){
2177                         HRESULT hRes = GetProcessDPIAwareness(hProcess, &value);
2178                         DBW("DPIAware: value=%d", value);
2179                         //SetProcessDPIAwareness(Process_System_DPI_Aware);
2180                         dpi_x = GetDeviceCaps(hdc, LOGPIXELSX);
2181                         dpi_y = GetDeviceCaps(hdc, LOGPIXELSY);
2182                         DBW("dpi: %d, %d", dpi_x, dpi_y);
2183                 } else {
2184                         dpi_x = ScaleX;
2185                         dpi_y = ScaleY;
2186                 }
2187                 for (int i=0;i<num;i++){
2188                         pts[i].x = MulDiv(pts[i].x, dpi_x, 96);
2189                         pts[i].y = MulDiv(pts[i].y, dpi_y, 96);
2190                 }
2191 #if 0
2192                 if (SetProcessDPIAwareness){
2193                         SetProcessDPIAwareness(value);
2194                 }
2195 #endif
2196         }
2197         if (hInst){
2198                 FreeLibrary(hInst);
2199         }
2200 #endif
2201 #else   // \8b\8c\83R\81[\83h
2202         HINSTANCE hInst = NULL;
2203         if (!GetProcessDPIAwareness){
2204                 hInst = LoadLibrary("shcore.dll");
2205                 DBW("shcore=%08X", hInst);
2206                 if (hInst){
2207                         GetProcessDPIAwareness = (FNGetProcessDPIAwareness)GetProcAddress(hInst, "GetProcessDPIAwareness");
2208                         SetProcessDPIAwareness = (FNSetProcessDPIAwareness)GetProcAddress(hInst, "SetProcessDPIAwareness");
2209                         DBW("DPI API:%08X %08X", GetProcessDPIAwareness, SetProcessDPIAwareness);
2210                 }
2211         }
2212         if (GetProcessDPIAwareness || (ScaleX && ScaleY)){
2213                 int dpi_x, dpi_y;
2214                 PROCESS_DPI_AWARENESS value;
2215                 if (GetProcessDPIAwareness && hdc){
2216                         HRESULT hRes = GetProcessDPIAwareness(hProcess, &value);
2217                         SetProcessDPIAwareness(Process_System_DPI_Aware);
2218                         dpi_x = GetDeviceCaps(hdc, LOGPIXELSX);
2219                         dpi_y = GetDeviceCaps(hdc, LOGPIXELSY);
2220                 } else {
2221                         dpi_x = ScaleX;
2222                         dpi_y = ScaleY;
2223                 }
2224                 for (int i=0;i<num;i++){
2225                         pts[i].x = MulDiv(pts[i].x, dpi_x, 96);
2226                         pts[i].y = MulDiv(pts[i].y, dpi_y, 96);
2227                 }
2228                 if (SetProcessDPIAwareness){
2229                         SetProcessDPIAwareness(value);
2230                 }
2231                 if (hInst){
2232                         FreeLibrary(hInst);
2233                 }
2234         }
2235 #endif
2236 }
2237
2238 int CALLBACK EnumMetaFileProc( HDC hdc, HANDLETABLE *ht, CONST ENHMETARECORD *mfr, int nobj, LPARAM /* user */ )
2239 {
2240         PlayEnhMetaFileRecord( hdc, ht, mfr, nobj );
2241
2242         //DBW("iType=%d",mfr->iType);
2243
2244         switch ( mfr->iType ){
2245                 case EMR_EXTTEXTOUTA:
2246                 case EMR_EXTTEXTOUTW:
2247                 {
2248                         EMREXTTEXTOUTW *emr = (EMREXTTEXTOUTW*)mfr;
2249
2250                         //DBW("(%d,%d) <%d=%d=%d=%d>", CursorPoint.x, CursorPoint.y, emr->rclBounds.left, emr->rclBounds.top,emr->rclBounds.right, emr->rclBounds.bottom);
2251 #if 1
2252                         if ( PtInRect( (RECT*)&emr->rclBounds, CursorPoint ) ){
2253                                 DBW("(%d,%d) <%d=%d>", CursorPoint.x, CursorPoint.y, emr->rclBounds.left, emr->emrtext.ptlReference.x);
2254 #if 0
2255                                 {
2256                                 SIZE sz1, sz2;
2257                                 GetWindowExtEx( hdc, &sz1 );
2258                                 GetViewportExtEx( hdc, &sz2 );
2259                                 DBW("%d-%d %d-%d", sz1.cx, sz1.cy, sz2.cx, sz2.cy);
2260                                 }
2261 #endif
2262                                 int loc;
2263                                 if ( mfr->iType == EMR_EXTTEXTOUTW ){
2264                                         //DBW("offString=%d nChars=%d left=%d top=%d offDx=%d", emr->emrtext.offString, emr->emrtext.nChars, emr->rclBounds.left, emr->rclBounds.top, emr->emrtext.offDx);
2265                                         //DBW("text=%ws", (wchar_t*) ( ((char*)emr) + emr->emrtext.offString ));
2266                                         loc = GetTextFromPoint( hdc, (wchar_t*) ( ((char*)emr) + emr->emrtext.offString ),
2267                                                 emr->emrtext.nChars,
2268                                                 CursorPoint.x - emr->rclBounds.left /* + emr->emrtext.ptlReference.x */,
2269                                                 CursorPoint.y - emr->rclBounds.top  /* + emr->emrtext.ptlReference.y */,
2270                                                 ((int*)(((char*)emr) + emr->emrtext.offDx)) );
2271                                 } else {
2272                                         loc = GetTextFromPoint( hdc, ((char*)emr) + emr->emrtext.offString,
2273                                                 emr->emrtext.nChars,
2274                                                 CursorPoint.x - emr->rclBounds.left /* + emr->emrtext.ptlReference.x */,
2275                                                 CursorPoint.y - emr->rclBounds.top  /* + emr->emrtext.ptlReference.y */,
2276                                                 ((int*)(((char*)emr) + emr->emrtext.offDx)) );
2277                                 }
2278                                 if ( loc != -1 ){
2279 //                                      char *buf = NULL;
2280                                         const char *text = ((char*)emr) + emr->emrtext.offString;
2281                                         int len = emr->emrtext.nChars;
2282                                         if ( mfr->iType == EMR_EXTTEXTOUTW ){
2283                                                 // WIDE
2284                                                 //DBW("len=%d loc=%d text=%ws", len, loc, text);
2285                                                 CallbackMain(DCH_HITTEXT2, text, len * sizeof(wchar_t), (HWND)loc);
2286 #if 0
2287                                                 // UNICODE->ANSI
2288                                                 // ANSI\8fã\82Å\82Ìloc\82ð\8b\81\82ß\82é\82½\82ß\81A\91O\94¼\82Æ\8cã\94¼\82ð\95ª\82¯\82Ä\95Ï\8a·
2289                                                 wchar_t *wp = (wchar_t*) ( ((char*)emr) + emr->emrtext.offString );
2290                                                 buf = new char[ emr->emrtext.nChars * 2 ];
2291                                                 memset( buf, 0, emr->emrtext.nChars*2 );
2292                                                 // \91O\94¼\95\94\95ª
2293                                                 len = 0;
2294                                                 if ( loc > 0 ){
2295                                                         len = WideCharToMultiByte( CP_ACP, 0, wp, loc,
2296                                                                 buf, emr->emrtext.nChars * 2, NULL, NULL );
2297                                                 }
2298                                                 int newloc = len;
2299                                                 // \8cã\94¼\95\94\95ª
2300                                                 if ( emr->emrtext.nChars > (unsigned int)loc ){
2301                                                         len += WideCharToMultiByte( CP_ACP, 0, wp+loc, emr->emrtext.nChars - loc,
2302                                                                 buf+len, emr->emrtext.nChars * 2 - len, NULL, NULL );
2303                                                 }
2304                                                 loc = newloc;
2305                                                 text = buf;
2306 #endif
2307
2308                                         } else {
2309                                                 // ANSI
2310                                                 CallbackMain(DCH_HITTEXT1, text, len, (HWND)loc);
2311                                         }
2312
2313                                         DBW("Found@Enum");
2314 #if 0
2315                                         CallbackMain(DCH_HITTEXT1, text, len, (HWND)loc);
2316                                         if ( buf )
2317                                                 delete buf;
2318 #endif
2319 #if 0
2320                                         {
2321                                         char b[100];
2322                                         sprintf(b,"exScale=%f eyScale=%f ptlReference=(%d,%d)",emr->exScale, emr->eyScale, emr->emrtext.ptlReference.x, emr->emrtext.ptlReference.y );
2323                                         DBW(b);
2324                                         DBW("iGraphicsMode=%d", emr->iGraphicsMode);
2325                                         }
2326 #endif
2327 #if 0
2328                                         {
2329                                                 for ( int i=0;i<(int)emr->emrtext.nChars;i++ ){
2330                                                         DBW(">%d", ((int*)(((char*)emr) + emr->emrtext.offDx))[i] );
2331                                                 }
2332                                         }
2333 #endif
2334 //                                      DBW("[%d %d][%d %d]text=(%s)", emr->rclBounds.left, emr->rclBounds.top, CursorPoint.x, CursorPoint.y, text);
2335 //                                      result = false; // stop enumration      // \8d\82\91¬\89»\82Ì\82½\82ß\93r\92\86\82Å\8fI\82í\82è\82É\82µ\82½\82¢\82ª\81E\81E\81E\82Ç\82¤\82µ\82æ\82¤\81H
2336 #if METAEXTTEXTOUT
2337                                         // prevent to get from ExtTextOut hook
2338                                         FoundLocA = -1;
2339                                         FoundLocW = -1;
2340 #endif
2341                                         HitFound = true;
2342                                 }
2343                         }
2344 #else   // for debug
2345                         if ( mfr->iType == EMR_EXTTEXTOUTW ){
2346                                 CallbackMain(DCH_EXTTEXTOUTW, emr, sizeof(EMREXTTEXTOUTW) + emr->emrtext.nChars * sizeof(wchar_t), (HWND)hdc);
2347                         } else {
2348                                 CallbackMain(DCH_EXTTEXTOUTA, emr, sizeof(EMREXTTEXTOUTA) + emr->emrtext.nChars, (HWND)hdc);
2349                         }
2350 #endif
2351                 }
2352                         break;
2353         }
2354         return true;
2355 }
2356
2357 }       // extern "C"
2358
2359 // text\82Ì\90æ\93ª\82ð(0,0)\82Æ\82µ\82½\8dÀ\95W\82Å\81Apos\82Ì\88Ê\92u\82É\82 \82étext\82Ì\95\8e\9a\88Ê\92u\82ð\95Ô\82·
2360 int GetTextFromPoint( HDC hdc, const char *text, int len, int pos_x, int pos_y, const int *dx )
2361 {
2362         if ( pos_x < 0 || pos_y < 0 ) return -1;
2363
2364         int count = 0;
2365         SIZE sz;
2366         int *rdx = NULL;
2367         if ( dx ){
2368                 rdx = new int[len];
2369                 memset( rdx, 0, len*sizeof(int) );
2370         }
2371         if ( !GetTextExtentExPointA( hdc, text, len, pos_x, &count, rdx, &sz ) ){
2372                 DBW("GetTextExtentExPointA Failure!!");
2373                 if ( rdx )
2374                         delete rdx;
2375                 return -1;
2376         }
2377 #if METAEXTTEXTOUT
2378         LastX += sz.cx; // update
2379 #endif
2380         // size over check
2381         if ( pos_y > sz.cy
2382                 || pos_x > sz.cx
2383                 ){
2384                 if ( rdx ) delete rdx;
2385                 return -1;
2386         }
2387         DBW("A:len=%d pos_x=%d sz.cx=%d", len, pos_x, sz.cx);
2388         if ( dx && count > 0 ){
2389                 // ex.
2390                 // Win98,Notepad\82Ì\93ú\96{\8cê\8fã\82Å
2391                 //  dx = 0, 8, 0, 8, 0, 8, ...
2392                 // rdx = 9,10, 9,10, 9,10, ...
2393 #if 0
2394                 {
2395                         int i;
2396                         for ( i=0;i<len;i++ ){
2397                                 DBW(" dx[%2d]=%d",i,dx[i]);
2398                         }
2399                         for ( i=0;i<count;i++ ){
2400                                 DBW("rdx[%2d]=%d",i,rdx[i+1]-rdx[i]);
2401                         }
2402                 }
2403 #endif
2404                 // spacing\82Ì\8cë\8d·\82ð\8cv\8eZ
2405                 // Times New Roman\82È\82Ç\82Å\92²\82×\82é\82Æ\82©\82È\82è\82Ì\8cë\8d·\82ª\82 \82é\81B\82È\82º\81H
2406
2407                 int i = 0;
2408                 int j = 0;
2409                 int sumdx = 0;
2410 //              DBW("rd(x)[0]=%d,%d",dx[0],rdx[0]);
2411                 if ( rdx[0] ){
2412                         if ( dx[0] ){
2413                                 sumdx = dx[0] - rdx[0];
2414                         } else {
2415                                 sumdx = dx[1] - rdx[0];
2416                         }
2417                         i++;
2418                         j++;
2419                 }
2420                 for ( ;i<count;i++,j++ ){
2421 #if 0
2422                         if ( rdx[i] == rdx[i-1] ){ j--; continue;}      // for multi-bytes font
2423                                                                                                                 //*++ \82 \82Æ\82Å ExtTextOut API manual\82ð\8eQ\8fÆ
2424                         sumdx += dx[j] - (rdx[i]-rdx[i-1]);
2425 //                      DBW("%3d <> %3d", dx[j], rdx[i]-rdx[i-1]);
2426 #else   // Win98\82Å\82Í\81Amulti-byte\82Å\82à\95ª\8eU\82³\82¹\82Ä\82¢\82é\8fê\8d\87\82ª\82 \82é\82½\82ß\81Adx\82Å\94»\92f
2427                         sumdx += (dx[j]?dx[j]:dx[j+1]) - (rdx[i]-rdx[i-1]);
2428 #endif
2429                 }
2430 //              DBW("sumdx=%d",sumdx);
2431                 if ( !GetTextExtentExPointA( hdc, text, len, pos_x - sumdx, &count, rdx, &sz ) ){
2432                         if ( rdx )
2433                                 delete rdx;
2434                         return -1;
2435                 }
2436         }
2437         if ( rdx )
2438                 delete rdx;
2439         return count;
2440 }
2441 int GetTextFromPoint( HDC hdc, const wchar_t *text, int len, int pos_x, int pos_y, const int *dx )
2442 {
2443 #if USE_VXD
2444         if (WindowsNT)
2445 #endif
2446         {
2447                 if ( pos_x < 0 || pos_y < 0 ) return -1;
2448
2449                 int count = 0;
2450                 SIZE sz;
2451                 int *rdx = NULL;
2452                 if ( dx ){
2453                         rdx = new int[ len ];
2454                         memset( rdx, 0, len );
2455                 }
2456                 if ( !GetTextExtentExPointW( hdc, text, len, pos_x, &count, rdx, &sz ) )
2457                 {
2458                         DBW("GetTextExtentExPointW Failure!!");
2459                         if ( rdx )
2460                                 delete[] rdx;
2461                         return -1;
2462                 }
2463 #if METAEXTTEXTOUT
2464                 LastX += sz.cx;
2465 #endif
2466                 // size over check
2467                 if ( pos_y > sz.cy
2468                         || pos_x > sz.cx
2469                         ){
2470                         if ( rdx ) delete[] rdx;
2471                         return -1;
2472                 }
2473                 DBW("W:len=%d pos_x=%d sz.cx=%d", len, pos_x, sz.cx);
2474                 if ( dx && count > 0 ){
2475                         // spacing\82Ì\8cë\8d·\82ð\8cv\8eZ
2476                         // Times New Roman\82È\82Ç\82Å\92²\82×\82é\82Æ\82©\82È\82è\82Ì\8cë\8d·\82ª\82 \82é\81B\82È\82º\81H
2477                         int i = 0;
2478                         int j = 0;
2479                         int sumdx = 0;
2480         //              DBW("rd(x)[0]=%d,%d",dx[0],rdx[0]);
2481                         if ( rdx[0] ){
2482                                 sumdx = dx[0] - rdx[0];
2483                                 i++;
2484                                 j++;
2485                         }
2486                         for ( ;i<count-1;i++,j++ ){
2487 #if 0
2488                                 if ( rdx[i] == rdx[i-1] ){ j--; continue;}      // for multi-bytes font
2489                                                                                                                 //*++ \82 \82Æ\82Å ExtTextOut API manual\82ð\8eQ\8fÆ
2490                                 sumdx += dx[j] - (rdx[i]-rdx[i-1]);
2491         //                      DBW("%3d <> %3d", dx[j], rdx[i]-rdx[i-1]);
2492 #else
2493                                 sumdx += (dx[j]?dx[j]:dx[j+1]) - (rdx[i]-rdx[i-1]);
2494 #endif
2495                         }
2496         //              DBW("sumdx=%d",sumdx);
2497                         if ( !GetTextExtentExPointW( hdc, text, len, pos_x - sumdx, &count, rdx, &sz ) ){
2498                                 if ( rdx )
2499                                         delete rdx;
2500                                 return -1;
2501                         }
2502                 }
2503                 if ( rdx )
2504                         delete rdx;
2505                 return (count == len && sz.cx < pos_x) ? -1 : count;
2506         }
2507 #if USE_VXD
2508         else {
2509                 char *buf = new char[ len * sizeof(wchar_t) ];
2510                 memset( buf, 0, len * sizeof(wchar_t) );
2511                 int ansilen = WideCharToMultiByte( CP_ACP, 0, text, len, buf, len*sizeof(wchar_t), NULL, NULL );
2512                 int r = GetTextFromPoint( hdc, buf, ansilen, pos_x, pos_y, dx );
2513                 delete buf;
2514                 return r;
2515         }
2516 #endif
2517 }
2518
2519 #define WMCD_EXISTCHECK         0x4000
2520 #define WMCD_SETPOINT           0x4001
2521
2522 class TDC {
2523         HDC hdc;
2524         HWND hwnd;
2525 public:
2526         TDC()
2527         :hwnd(NULL)
2528         {
2529                 hdc = GetDC(NULL);
2530         }
2531         TDC(HWND _hwnd)
2532         :hwnd(_hwnd)
2533         {
2534                 hdc = GetWindowDC(hwnd);
2535         }
2536         ~TDC()
2537         {
2538                 reset();
2539         }
2540         void reset()
2541         {
2542                 if (hdc){
2543                         ReleaseDC(hwnd, hdc);
2544                         hdc = NULL;
2545                 }
2546         }
2547         operator HDC() { return hdc; }
2548         bool operator !() { return hdc==NULL; }
2549 };
2550
2551 bool CaptureImage(HWND hwnd, bool movesend, bool non_block)
2552 {
2553         MoveSendMode = movesend;
2554         CaptureImageBlocking = false;
2555
2556         bool capture_page = false;
2557         if (hwndAMODI){
2558                 capture_page = SendMessage(hwndAMODI, WM_AMODI, AMODI_CMD_PAGE_CAPTURE, 0) ? true : false;
2559         }
2560
2561         // Get the rect of the target window.
2562         RECT rcTarget;
2563         if (!GetWindowRect(hwnd, &rcTarget)){
2564                 // window died?
2565                 return false;
2566         }
2567         if (!ExtAMODI){
2568                 if (!IsWindowEnabled(hwndAMODI)){
2569                         // AMODI died?
2570                         hwndAMODI = FindAMODI();
2571                         if (!hwndAMODI)
2572                                 return false;
2573                 }
2574         }
2575         int w = rcTarget.right - rcTarget.left;
2576         int h = rcTarget.bottom - rcTarget.top;
2577         if (w==0 || h==0){
2578                 return false;   // no area in the target.
2579         }
2580
2581         POINT ptCursor; // \89æ\91\9c\8fã\82Ì\83J\81[\83\\83\8b\88Ê\92u
2582         int x, y;
2583         if (capture_page){
2584                 x = rcTarget.left;
2585                 y = rcTarget.top;
2586                 ptCursor.x = ScreenPoint.x - rcTarget.left;
2587                 ptCursor.y = ScreenPoint.y - rcTarget.top;
2588         } else {
2589                 // x\95û\8cü : target rect\82Ì\8d\92[\82©\82ç
2590                 // y\95û\8cü : cursor point\82Ì\8fã\89º100 pixel
2591                 x = rcTarget.left;
2592                 int offs = 100;
2593                 if (ScreenPoint.y - rcTarget.top < offs){
2594                         if (ScreenPoint.y < rcTarget.top) return false; // click on out of rect?
2595                         y = rcTarget.top;
2596                         h = ScreenPoint.y - rcTarget.top + offs;
2597                 } else {
2598                         y = ScreenPoint.y - offs;
2599                         h = offs * 2;
2600                 }
2601                 if (y+h>rcTarget.bottom){
2602                         h = rcTarget.bottom - y;
2603                 }
2604                 ptCursor.x = ScreenPoint.x - rcTarget.left;
2605                 ptCursor.y = ScreenPoint.y - y;
2606         }
2607
2608         if (0){
2609                 HWND hwnd = GetDesktopWindow();
2610                 RECT rc;
2611                 GetWindowRect(hwnd, &rc);
2612                 x = 0;
2613                 y = 0;
2614                 w = rc.right - rc.left;
2615                 h = rc.bottom - rc.top;
2616         }
2617
2618         if (!capture_page){
2619                 // Notify start enumrate
2620                 CallbackMain(DCH_START, &CursorPoint, sizeof(CursorPoint), hwnd);
2621         }
2622
2623         bool ok = false;
2624
2625         TDC hdc;
2626
2627         if (!hdc){
2628                 goto jend;
2629         }
2630
2631 #if USE_SCALING
2632         POINT pts[3];
2633         pts[0].x = x;
2634         pts[0].y = y;
2635         pts[1].x = w;
2636         pts[1].y = h;
2637         pts[2].x = ptCursor.x;
2638         pts[2].y = ptCursor.y;
2639         DoScale(hdc, pts, 3);
2640         //DBW("%d,%d %d,%d,%d,%d -> %d,%d %d,%d,%d,%d", ptCursor.x, ptCursor.y, x, y, w, h, pts[2].x, pts[2].y, pts[0].x, pts[0].y, pts[1].x, pts[1].y);
2641         x = pts[0].x;
2642         y = pts[0].y;
2643         w = pts[1].x;
2644         h = pts[1].y;
2645         ptCursor.x = pts[2].x;
2646         ptCursor.y = pts[2].y;
2647 #endif
2648
2649         // capture image
2650
2651         int wlen = (w*3+3)&~3;
2652
2653         /* \8f\91\82«\8d\9e\82Ý\97p\83o\83b\83t\83@\82Ì\83T\83C\83Y\8cv\8eZ */
2654         DWORD dwFSize = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER) + wlen * h;
2655
2656         /* \83o\83b\83t\83@\8am\95Û\82Æ\83|\83C\83\93\83^\90Ý\92è */
2657         LPBYTE lpBuf = (LPBYTE)new char[dwFSize];
2658         if (!lpBuf){
2659                 goto jend;
2660         }
2661
2662         LPBITMAPFILEHEADER lpHead = (LPBITMAPFILEHEADER)lpBuf;
2663         LPBITMAPINFOHEADER lpInfo = (LPBITMAPINFOHEADER)(lpBuf+sizeof(BITMAPFILEHEADER));
2664         LPBYTE lpPixel = lpBuf+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
2665
2666         /* 24\83r\83b\83gBMP\83t\83@\83C\83\8b\82Ì\83w\83b\83_\8dì\90¬ */
2667         lpHead->bfType = ('M'<<8) +'B';
2668         lpHead->bfSize = dwFSize;
2669         lpHead->bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
2670         lpInfo->biSize = sizeof(BITMAPINFOHEADER);
2671         lpInfo->biWidth = w;
2672         lpInfo->biHeight = h;
2673         lpInfo->biPlanes = 1;
2674         lpInfo->biBitCount = 24;
2675
2676         HBITMAP hBmp = CreateCompatibleBitmap(hdc, w, h);
2677         if (hBmp){
2678                 HDC hdcMem = CreateCompatibleDC(hdc);
2679                 if (hdcMem){
2680                         HDC hOld = (HDC)SelectObject(hdcMem, hBmp);
2681                         if (hOld!=(HDC)GDI_ERROR){
2682                                 BOOL r = BitBlt(hdcMem, 0, 0, w, h, hdc, x, y, SRCCOPY);
2683                                 SelectObject(hdcMem, hOld);
2684                                 if (r){
2685 //                                      int lines = GetDIBits(hdc, hBmp, 0, h, NULL, (LPBITMAPINFO)lpInfo, DIB_RGB_COLORS);
2686                                         int lines = GetDIBits(hdc, hBmp, 0, h, lpPixel, (LPBITMAPINFO)lpInfo, DIB_RGB_COLORS);
2687                                         if (lines!=0){
2688                                                 ok = true;
2689                                         } else {
2690                                                 dbw("GetDIBits error??? %d h=%d w=%d bfSize=%d", GetLastError(), h, w, dwFSize);
2691                                         }
2692                                 } else {
2693 //                                              dbw("BitBlt error??? %d", GetLastError());
2694                                 }
2695                         }
2696                         DeleteObject(hdcMem);
2697                 }
2698                 DeleteObject(hBmp);
2699         }
2700
2701         hdc.reset();
2702
2703         if (ok){
2704                 ok = false;
2705
2706                 //TCHAR path[sizeof(AMODIPath)+40];
2707                 TCHAR *path = ImageTextPath;
2708                 size_t path_size = sizeof(ImageTextPath);
2709                 size_t len;
2710                 if (ExtAMODI){
2711                         len = _tcslen(AMODIPath);
2712                         _tcscpy(path, AMODIPath);
2713                 } else {
2714                         memset(path, 0, path_size);
2715                         len = GetTempPath((DWORD)path_size, path);
2716                 }
2717                 if (len>0){
2718                         // send image to AMODI
2719                         SYSTEMTIME t;
2720                         GetLocalTime(&t);
2721                         if (ExtAMODI){
2722                                 wsprintf(path+len, /*path_size-len,*/ _T("\\%04d-%02d-%02d-%02d%02d%02d-(%d,%d).bmp"),
2723                                         t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, ptCursor.x, ptCursor.y);
2724                         } else {
2725                                 wsprintf(path+len, /*path_size-len,*/ _T("\\amodi\\%04d-%02d-%02d-%02d%02d%02d.bmp"),
2726                                         t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
2727                                 SendAMODI(WMCD_SETPOINT, (char*)&ptCursor, sizeof(ptCursor));
2728                         }
2729                         HANDLE fh = CreateFile(path,  GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2730                         if (fh!=INVALID_HANDLE_VALUE){
2731                                 DWORD dwSize;
2732                                 WriteFile(fh, lpBuf, dwFSize, &dwSize, NULL);
2733                                 CloseHandle(fh);
2734                                 SaveImageTime = GetTickCount();
2735
2736                                 if (capture_page){
2737                                         ok = true;
2738                                 } else {
2739                                         len = (int)_tcslen(path);
2740                                         _tcsncat(path+len, _T(".txt"), path_size-len);
2741                                         if (non_block){
2742                                                 CaptureImageBlocking = true;
2743                                         } else {
2744                                                 if (WaitAndGetResult(path, 3000))
2745                                                         ok = true;
2746                                         }
2747                                 }
2748                         }
2749                 }
2750         }
2751         delete[] lpBuf;
2752
2753 jend:
2754         if (!CaptureImageBlocking){
2755                 if (!capture_page){
2756                         CallbackMain(DCH_END | (MoveSendMode ? DCH_MOVESEND : 0), NULL, 0, hwnd );
2757                 }
2758         }
2759
2760         return ok;
2761 }
2762
2763 bool WaitAndGetResult(const TCHAR *path, unsigned waittime)
2764 {
2765         bool ok = false;
2766
2767         // wait and get text from AMODI
2768
2769         HANDLE fh = WaitForResult(path, waittime);
2770
2771         CaptureImageBlocking = false;
2772
2773         if (fh==INVALID_HANDLE_VALUE){
2774                 DBW("file open timeout");
2775                 CheckAMODIAlive();
2776         } else {
2777                 DWORD size = GetFileSize(fh, NULL);
2778                 if (size>0){
2779                         unsigned bufsize = size+sizeof(wchar_t);
2780                         char *text = new char[bufsize];
2781                         if (text){
2782                                 DWORD rbyte;
2783                                 if (ReadFile(fh, text, size, &rbyte, NULL)){
2784                                         if (rbyte==size){
2785                                                 *(wchar_t*)&text[size] = '\0';
2786                                                 // text\82Ì\82P\8ds\96Ú\82Í\89ð\90Í\8fî\95ñ
2787                                                 // format
2788                                                 // (\83}\83E\83X\83J\81[\83\\83\8b\82Ì\82 \82é\83e\83L\83X\83g\88Ê\92u[\95\8e\9a\96Ú zero-index])
2789                                                 int loc = 0;
2790                                                 int col = 0;
2791                                                 wchar_t *p = (wchar_t*)text;
2792                                                 while (*p){
2793                                                         wchar_t c = *p++;
2794                                                         if (c=='\n'){
2795                                                                 break;
2796                                                         }
2797                                                         if (col==0){
2798                                                                 loc = _wtoi(p);
2799                                                                 col++;
2800                                                         }
2801                                                 }
2802
2803                                                 DBW("%d:%ws", loc, p);
2804                                                 CallbackMain(DCH_HITTEXT2, p, bufsize - (int)((char*)p-text), (HWND)loc);
2805
2806                                                 ok = true;
2807                                         }
2808                                 }
2809                                 delete[] text;
2810                         }
2811                 }
2812                 CloseHandle(fh);
2813                 DeleteFile(path);
2814         }
2815         CallbackMain(DCH_END | (MoveSendMode ? DCH_MOVESEND : 0), NULL, 0, NULL );
2816         return ok;
2817 }
2818
2819 HANDLE WaitForResult(const TCHAR *path, unsigned waittime)
2820 {
2821         HANDLE fh = INVALID_HANDLE_VALUE;
2822
2823         while (1){
2824                 fh = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
2825                 if (fh!=INVALID_HANDLE_VALUE)
2826                         break;
2827
2828                 DWORD now = GetTickCount();
2829                 if (now-SaveImageTime > waittime)
2830                         break;
2831
2832                 Sleep(10);
2833         }
2834
2835         return fh;
2836 }
2837
2838 #define APPNAME _T("Auto MODI")
2839
2840 static HWND hwndFind;
2841 static BOOL CALLBACK EnumWindowsProc( HWND hwnd, LPARAM lParam )
2842 {
2843         TCHAR wndname[80];
2844         if (GetWindowText(hwnd, wndname, tsizeof(wndname))<0){
2845                 return TRUE;
2846         }
2847         if (_tcscmp(wndname, APPNAME)){ return TRUE; }
2848
2849         COPYDATASTRUCT cd;
2850         cd.dwData = WMCD_EXISTCHECK;
2851         cd.lpData = (void*)APPNAME;
2852         cd.cbData = (DWORD)(_tcslen(APPNAME)+1)*sizeof(TCHAR);
2853         if ( SendMessage( hwnd, WM_COPYDATA, 0, (LPARAM)&cd ) )
2854         {
2855                 // found
2856                 hwndFind = hwnd;
2857                 return FALSE;
2858         }
2859         return TRUE;
2860 }
2861
2862 HWND FindAMODI()
2863 {
2864         hwndFind = NULL;
2865         EnumWindows(EnumWindowsProc, 0);
2866         return hwndFind;
2867 }
2868
2869 int SendAMODI(int cmd, const char *data, int len)
2870 {
2871         COPYDATASTRUCT cd;
2872         cd.dwData = cmd;
2873         cd.lpData = (void*)data;
2874         cd.cbData = len;
2875         return (int)SendMessage(hwndAMODI, WM_COPYDATA, 0, (LPARAM)&cd);
2876 }
2877
2878 void CheckAMODIAlive()
2879 {
2880         CallbackMain(DCH_LAUNCH_AMODI, NULL, 0, 0);
2881 }
2882
2883 void SendMoveMessage()
2884 {
2885 #if MOVESEND_POST
2886         PostMessage(hwndCallback, WM_MOVESEND, MouseMoving ? 0 : -1, 0);
2887 #else
2888 //      CallbackMain(DCH_MOVESEND, pt, sizeof(*pt), 0);
2889         MouseMoving = true;
2890         if (SendMoveEvent) SetEvent(SendMoveEvent);
2891 #endif
2892 }
2893 void SendCancelMove()
2894 {
2895 #if MOVESEND_POST
2896         PostMessage(hwndCallback, WM_MOVESEND, MouseMoving ? 0 : -1, 0);
2897 #else
2898 //      CallbackMain(DCH_MOVESEND, NULL, 0, (HWND)-1);
2899         MouseMoving = false;
2900         if (SendMoveEvent) SetEvent(SendMoveEvent);
2901 #endif
2902 }
2903
2904 #if !MOVESEND_POST
2905 // main program\82ÌWindows message\8f\88\97\9d\82ª\8fd\82¢\82Æ\81ACalblackMain\82à\8fd\82­\82È\82é\82½\82ß\81A
2906 // mouse move\82Í\95Êthread\82Å\8f\88\97\9d
2907 DWORD WINAPI SendMoveThread(LPVOID vdParam)
2908 {
2909         while(1){
2910                 if (WaitForSingleObject(SendMoveEvent, INFINITE) != WAIT_OBJECT_0){
2911                         break;
2912                 }
2913                 CallbackMain(DCH_MOVESEND, NULL, 0, (HWND)(MouseMoving ? 0 : -1));
2914         }
2915         return 0;
2916 }
2917 #endif
2918
2919 #if EXC_WOW64 && defined(_M_X64)
2920 void CheckWOW64()
2921 {
2922         typedef BOOL (WINAPI *FNIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process);
2923
2924         FNIsWow64Process _IsWow64Process = (FNIsWow64Process)GetProcAddress(GetModuleHandle("kernel32"),"IsWow64Process");
2925         if (_IsWow64Process){
2926                 BOOL flag = FALSE;
2927                 if (_IsWow64Process(hProcess, &flag)){
2928                         fWow64 = int_bool(flag);
2929                 }
2930         }
2931 }
2932 #endif
2933
2934 bool EnablePrivilege(LPTSTR lpszPrivilege, bool bEnable)
2935 {
2936         BOOL             bResult;
2937         LUID             luid;
2938         HANDLE           hToken;
2939         TOKEN_PRIVILEGES tokenPrivileges;
2940
2941         if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2942                 return false;
2943         
2944         if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid)) {
2945                 CloseHandle(hToken);
2946                 return false;
2947         }
2948
2949         tokenPrivileges.PrivilegeCount           = 1;
2950         tokenPrivileges.Privileges[0].Luid       = luid;
2951         tokenPrivileges.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
2952         
2953         bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
2954         
2955         CloseHandle(hToken);
2956
2957         return bResult && GetLastError() == ERROR_SUCCESS;
2958 }
2959
2960 /*======================================================================//
2961 //      DllMain
2962 //----------------------------------------------------------------------//
2963 // Description:
2964 //
2965 // Arguments:
2966 //
2967 // Return Value:
2968 //
2969 //======================================================================*/
2970 #ifdef _MSC_VER
2971 BOOL WINAPI DllMain(HINSTANCE hInst, DWORD reason, LPVOID )
2972 #else
2973 int WINAPI DllEntryPoint(HINSTANCE hInst, DWORD reason, LPVOID)
2974 #endif
2975 {
2976         switch ( reason ){
2977                 case DLL_PROCESS_ATTACH:
2978                         hInstance = hInst;
2979                         idProcess = GetCurrentProcessId();
2980                         for (int i=0;i<2;i++){
2981                                 hProcess = OpenProcess( PROCESS_ALL_ACCESS|PROCESS_VM_WRITE|PROCESS_VM_OPERATION, TRUE, idProcess );
2982                                 if ( hProcess ){
2983 #if USE_DBW
2984                                         DBW("Attach %d(%08X)-%d : %08X", idProcess, hProcess, attach++,_ExtTextOutA);
2985 #endif
2986                                         break;
2987                                 } else {
2988                                         DBW("OpenProcess Error: %08X %d", idProcess, GetLastError());
2989                                         if (i==0){
2990                                                 if (!EnablePrivilege(SE_DEBUG_NAME, true)) {
2991                                                         break;  // failed
2992                                                 }
2993                                         }
2994                                 }
2995                         }
2996 #if EXC_WOW64 && defined(_M_X64)
2997                         CheckWOW64();
2998 #ifdef _WIN64
2999                         if (fWow64){
3000                                 DBW("WOW64 true");
3001                                 return FALSE;
3002                         }
3003 #else
3004                         if (!fWow64){
3005                                 DBW("WOW64 false");
3006                                 return FALSE;
3007                         }
3008 #endif
3009                         DBW("fWow64=%d", fWow64);
3010 #endif
3011                         if (siPageSize==0){
3012                                 SYSTEM_INFO si;
3013                                 GetSystemInfo( &si );
3014                                 siPageSize = si.dwPageSize;
3015                         }
3016                         hInstSHCore = LoadLibrary(_T("shcore.dll"));
3017 #if !MOVESEND_POST
3018                         SendMoveEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
3019                         CreateThread(NULL , 0 , SendMoveThread , NULL , 0 , &SendMoveThreadId);
3020 #endif
3021                         break;
3022                 case DLL_PROCESS_DETACH:
3023 //                      UNPROTECT_SHARE();
3024 #if !MOVESEND_POST
3025                         if (SendMoveEvent){
3026                                 CloseHandle(SendMoveEvent);
3027                                 SendMoveEvent = NULL;
3028                         }
3029 #endif
3030                         if (hInstSHCore){
3031                                 FreeLibrary(hInstSHCore);
3032                                 hInstSHCore = NULL;
3033                         }
3034 #if USE_DBW
3035                         DBW("Detach %d-%d", GetCurrentProcessId(),--attach);
3036 #endif
3037                         if ( hProcess ){
3038                                 CloseHandle( hProcess );
3039                         }
3040                         break;
3041         }
3042         return TRUE;
3043 }
3044 //---------------------------------------------------------------------------
3045 static HWND hWin = NULL;
3046 static const char *clsname = "TDbgMsgForm";
3047 static const char *winname = "Debug Messenger";
3048 void dbw( const char *format, ... )
3049 {
3050         if ( !hWin ){
3051                 hWin = FindWindowA( clsname, winname );
3052                 if ( !hWin ) return;
3053         }
3054         va_list ap;
3055         va_start( ap, format );
3056         char buf[ 2048 ];
3057 #ifdef _WIN64
3058         strcpy(buf, "x64:");
3059         wvsprintfA( buf+4, format, ap );
3060 #else
3061         wvsprintfA( buf, format, ap );
3062 #endif
3063         COPYDATASTRUCT cds;
3064         cds.dwData = 1; // Indicate String
3065         cds.cbData = (DWORD)strlen(buf);
3066         cds.lpData = buf;
3067         SendMessage( hWin, WM_COPYDATA, NULL, (LPARAM)&cds );
3068         va_end( ap );
3069 }