TB2Common.pas 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. unit TB2Common;
  2. {
  3. Toolbar2000
  4. Copyright (C) 1998-2005 by Jordan Russell
  5. All rights reserved.
  6. The contents of this file are subject to the "Toolbar2000 License"; you may
  7. not use or distribute this file except in compliance with the
  8. "Toolbar2000 License". A copy of the "Toolbar2000 License" may be found in
  9. TB2k-LICENSE.txt or at:
  10. http://www.jrsoftware.org/files/tb2k/TB2k-LICENSE.txt
  11. Alternatively, the contents of this file may be used under the terms of the
  12. GNU General Public License (the "GPL"), in which case the provisions of the
  13. GPL are applicable instead of those in the "Toolbar2000 License". A copy of
  14. the GPL may be found in GPL-LICENSE.txt or at:
  15. http://www.jrsoftware.org/files/tb2k/GPL-LICENSE.txt
  16. If you wish to allow use of your version of this file only under the terms of
  17. the GPL and not to allow others to use your version of this file under the
  18. "Toolbar2000 License", indicate your decision by deleting the provisions
  19. above and replace them with the notice and other provisions required by the
  20. GPL. If you do not delete the provisions above, a recipient may use your
  21. version of this file under either the "Toolbar2000 License" or the GPL.
  22. $jrsoftware: tb2k/Source/TB2Common.pas,v 1.31 2005/06/29 20:10:10 jr Exp $
  23. }
  24. interface
  25. {$I TB2Ver.inc}
  26. uses
  27. Windows, Classes, SysUtils, Messages, Controls, Forms;
  28. type
  29. TListSortExCompare = function(const Item1, Item2, ExtraData: Pointer): Integer;
  30. THandleWMPrintNCPaintProc = procedure(Control: TControl; Wnd: HWND; DC: HDC; AppData: Longint);
  31. function AddToFrontOfList(var List: TList; Item: Pointer): Boolean;
  32. function AddToList(var List: TList; Item: Pointer): Boolean;
  33. function ApplicationIsActive: Boolean;
  34. function AreFlatMenusEnabled: Boolean;
  35. function AreKeyboardCuesEnabled: Boolean;
  36. function CallTrackMouseEvent(const Wnd: HWND; const Flags: DWORD): Boolean;
  37. function CreateHalftoneBrush: HBRUSH;
  38. function CreateNullRegion: HRGN;
  39. function CreateRotatedFont(DC: HDC): HFONT;
  40. function DivRoundUp(const Dividend, Divisor: Integer): Integer;
  41. procedure DrawHalftoneInvertRect(const DC: HDC; const NewRect, OldRect: PRect;
  42. const NewSize, OldSize: TSize);
  43. procedure DrawRotatedText(const DC: HDC; AText: String; const ARect: TRect;
  44. const AFormat: Cardinal);
  45. procedure DrawInvertRect(const DC: HDC; const NewRect, OldRect: PRect;
  46. const NewSize, OldSize: TSize; const Brush: HBRUSH; BrushLast: HBRUSH);
  47. function EscapeAmpersands(const S: String): String;
  48. function FindAccelChar(const S: String): Char;
  49. function GetInputLocaleCodePage: UINT;
  50. function GetMenuShowDelay: Integer;
  51. function GetRectOfMonitorContainingPoint(const P: TPoint; const WorkArea: Boolean): TRect;
  52. function GetRectOfMonitorContainingRect(const R: TRect; const WorkArea: Boolean): TRect;
  53. function GetRectOfMonitorContainingWindow(const W: HWND; const WorkArea: Boolean): TRect;
  54. function GetRectOfPrimaryMonitor(const WorkArea: Boolean): TRect;
  55. function GetTextHeight(const DC: HDC): Integer;
  56. function GetTextWidth(const DC: HDC; S: String; const Prefix: Boolean): Integer;
  57. procedure HandleWMPrint(Control: TControl; const Wnd: HWND; var Message: TMessage;
  58. const NCPaintFunc: THandleWMPrintNCPaintProc; const AppData: Longint);
  59. procedure HandleWMPrintClient(const Control: TWinControl;
  60. var Message: TMessage);
  61. procedure ListSortEx(const List: TList; const Compare: TListSortExCompare;
  62. const ExtraData: Pointer);
  63. function Max(A, B: Integer): Integer;
  64. function Min(A, B: Integer): Integer;
  65. function MethodsEqual(const M1, M2: TMethod): Boolean;
  66. function NeedToPlaySound(const Alias: String): Boolean;
  67. procedure ProcessPaintMessages;
  68. procedure RemoveMessages(const AMin, AMax: Integer);
  69. procedure RemoveFromList(var List: TList; Item: Pointer);
  70. procedure SelectNCUpdateRgn(Wnd: HWND; DC: HDC; Rgn: HRGN);
  71. function StripAccelChars(const S: String; IncludingStandaloneKey: Boolean = False {MP}): String;
  72. function StripTrailingPunctuation(const S: String): String;
  73. function UsingMultipleMonitors: Boolean;
  74. const
  75. PopupMenuWindowNCSize = 3;
  76. DT_HIDEPREFIX = $00100000;{$EXTERNALSYM DT_HIDEPREFIX}
  77. var
  78. TrackMouseEventFunc: function(var EventTrack: TTrackMouseEvent): BOOL; stdcall;
  79. implementation
  80. uses
  81. TB2Version, Types, System.Character {MP};
  82. function ApplicationIsActive: Boolean;
  83. { Returns True if the application is in the foreground }
  84. begin
  85. Result := GetActiveWindow <> 0;
  86. end;
  87. procedure ListSortEx(const List: TList; const Compare: TListSortExCompare;
  88. const ExtraData: Pointer);
  89. { Similar to TList.Sort, but lets you pass a user-defined ExtraData pointer }
  90. procedure QuickSortEx(L: Integer; const R: Integer);
  91. var
  92. I, J: Integer;
  93. P: Pointer;
  94. begin
  95. repeat
  96. I := L;
  97. J := R;
  98. P := List[(L + R) shr 1];
  99. repeat
  100. while Compare(List[I], P, ExtraData) < 0 do Inc(I);
  101. while Compare(List[J], P, ExtraData) > 0 do Dec(J);
  102. if I <= J then
  103. begin
  104. List.Exchange(I, J);
  105. Inc(I);
  106. Dec(J);
  107. end;
  108. until I > J;
  109. if L < J then QuickSortEx(L, J);
  110. L := I;
  111. until I >= R;
  112. end;
  113. begin
  114. if List.Count > 1 then
  115. QuickSortEx(0, List.Count-1);
  116. end;
  117. type
  118. PPrintEnumProcData = ^TPrintEnumProcData;
  119. TPrintEnumProcData = record
  120. PrintChildren: Boolean;
  121. ParentWnd: HWND;
  122. DC: HDC;
  123. PrintFlags: LPARAM;
  124. end;
  125. function PrintEnumProc(Wnd: HWND; LParam: LPARAM): BOOL; stdcall;
  126. var
  127. R: TRect;
  128. SaveIndex: Integer;
  129. begin
  130. Result := True; { continue enumerating }
  131. with PPrintEnumProcData(LParam)^ do begin
  132. { Skip window if it isn't a child/owned window of ParentWnd or isn't visible }
  133. if (HWND(GetWindowLong(Wnd, GWL_HWNDPARENT)) <> ParentWnd) or
  134. (GetWindowLong(Wnd, GWL_STYLE) and WS_VISIBLE = 0) then
  135. { ^ don't use IsWindowVisible since it returns False if the window's
  136. parent window is not visible }
  137. Exit;
  138. GetWindowRect(Wnd, R);
  139. MapWindowPoints(0, ParentWnd, R, 2);
  140. SaveIndex := SaveDC(DC);
  141. { Like Windows, offset the window origin to the top-left coordinates of
  142. the child/owned window }
  143. MoveWindowOrg(DC, R.Left, R.Top);
  144. { Like Windows, intersect the clipping region with the entire rectangle of
  145. the child/owned window }
  146. OffsetRect(R, -R.Left, -R.Top);
  147. IntersectClipRect(DC, R.Left, R.Top, R.Right, R.Bottom);
  148. { Send a WM_PRINT message to the child/owned window }
  149. SendMessage(Wnd, WM_PRINT, WPARAM(DC), PrintFlags);
  150. { Restore the DC's state, in case the WM_PRINT handler didn't put things
  151. back the way it found them }
  152. RestoreDC(DC, SaveIndex);
  153. end;
  154. end;
  155. procedure HandleWMPrint(Control: TControl; const Wnd: HWND; var Message: TMessage;
  156. const NCPaintFunc: THandleWMPrintNCPaintProc; const AppData: Longint);
  157. { note: AppData is an application-defined value which is passed to NCPaintFunc }
  158. var
  159. DC: HDC;
  160. SaveIndex, SaveIndex2: Integer;
  161. R: TRect;
  162. P: TPoint;
  163. Data: TPrintEnumProcData;
  164. begin
  165. if (Message.LParam and PRF_CHECKVISIBLE = 0) or IsWindowVisible(Wnd) then begin
  166. DC := HDC(Message.WParam);
  167. SaveIndex2 := SaveDC(DC);
  168. try
  169. if Message.LParam and PRF_NONCLIENT <> 0 then begin
  170. SaveIndex := SaveDC(DC);
  171. if Assigned(NCPaintFunc) then
  172. NCPaintFunc(Control, Wnd, DC, AppData);
  173. RestoreDC(DC, SaveIndex);
  174. end;
  175. { Calculate the difference between the top-left corner of the window
  176. and the top-left corner of its client area }
  177. GetWindowRect(Wnd, R);
  178. P.X := 0; P.Y := 0;
  179. ClientToScreen(Wnd, P);
  180. Dec(P.X, R.Left); Dec(P.Y, R.Top);
  181. if Message.LParam and PRF_CLIENT <> 0 then begin
  182. { Like Windows, the flags PRF_ERASEBKGND, PRF_CHILDREN, and PRF_OWNED
  183. are ignored if PRF_CLIENT isn't also specified }
  184. if Message.LParam and PRF_ERASEBKGND <> 0 then begin
  185. { Send WM_ERASEBKGND }
  186. SaveIndex := SaveDC(DC);
  187. if Message.LParam and PRF_NONCLIENT <> 0 then
  188. MoveWindowOrg(DC, P.X, P.Y);
  189. SendMessage(Wnd, WM_ERASEBKGND, Message.WParam, 0);
  190. RestoreDC(DC, SaveIndex);
  191. end;
  192. { Send WM_PRINTCLIENT }
  193. SaveIndex := SaveDC(DC);
  194. if Message.LParam and PRF_NONCLIENT <> 0 then
  195. MoveWindowOrg(DC, P.X, P.Y);
  196. SendMessage(Wnd, WM_PRINTCLIENT, Message.WParam, 0);
  197. RestoreDC(DC, SaveIndex);
  198. { Like Windows, always offset child/owned windows by the size of the
  199. client area even if PRF_NONCLIENT isn't specified (a bug?) }
  200. MoveWindowOrg(DC, P.X, P.Y);
  201. Data.ParentWnd := Wnd;
  202. Data.DC := DC;
  203. { Send WM_PRINT to child/owned windows }
  204. if Message.LParam and PRF_CHILDREN <> 0 then begin
  205. Data.PrintChildren := True;
  206. Data.PrintFlags := PRF_NONCLIENT or PRF_CLIENT or PRF_ERASEBKGND or
  207. PRF_CHILDREN; { same flags as Windows passes to children }
  208. EnumChildWindows(Wnd, @PrintEnumProc, LPARAM(@Data));
  209. end;
  210. if Message.LParam and PRF_OWNED <> 0 then begin
  211. Data.PrintChildren := False;
  212. Data.PrintFlags := Message.LParam;
  213. EnumWindows(@PrintEnumProc, LPARAM(@Data));
  214. end;
  215. end;
  216. finally
  217. RestoreDC(DC, SaveIndex2);
  218. end;
  219. end;
  220. { Windows' WM_PRINT returns 1. I'm not sure why. }
  221. Message.Result := 1;
  222. end;
  223. type
  224. TWinControlAccess = class(TWinControl);
  225. procedure HandleWMPrintClient(const Control: TWinControl; var Message: TMessage);
  226. var
  227. Msg: TWMPaint;
  228. SaveIndex: Integer;
  229. begin
  230. Msg.Msg := WM_PAINT;
  231. Msg.DC := HDC(Message.WParam);
  232. Msg.Unused := 0;
  233. Msg.Result := 0;
  234. SaveIndex := SaveDC(HDC(Message.WParam));
  235. try
  236. TWinControlAccess(Control).PaintHandler(Msg);
  237. finally
  238. RestoreDC(HDC(Message.WParam), SaveIndex);
  239. end;
  240. end;
  241. function DivRoundUp(const Dividend, Divisor: Integer): Integer;
  242. { Similar to the 'div' operator, but if there is a remainder it always rounds
  243. the result up one (or down if the result is negative). }
  244. asm
  245. mov ecx, edx
  246. cdq
  247. idiv ecx
  248. test edx, edx
  249. jz @@1
  250. test eax, eax
  251. jns @@2
  252. dec eax
  253. jmp @@1
  254. @@2:
  255. inc eax
  256. @@1:
  257. end;
  258. function GetTextHeight(const DC: HDC): Integer;
  259. var
  260. TextMetric: TTextMetric;
  261. begin
  262. GetTextMetrics(DC, TextMetric);
  263. Result := TextMetric.tmHeight;
  264. end;
  265. function StripAccelChars(const S: String; IncludingStandaloneKey: Boolean {MP}): String;
  266. var
  267. I: Integer;
  268. begin
  269. Result := S;
  270. I := 1;
  271. while I <= Length(Result) do begin
  272. if not CharInSet(Result[I], LeadBytes) then begin
  273. if Result[I] = '&' then
  274. begin
  275. {MP}
  276. // Trim trailing artificial accelerators typical for asian translation
  277. // e.g. "ローカル(&L)"
  278. if IncludingStandaloneKey and
  279. (I = Length(Result) - 2) and
  280. (Result[I - 1] = '(') and
  281. Result[I + 1].IsLetter() and
  282. (Result[I + 2] = ')') then
  283. begin
  284. System.Delete(Result, I - 1, 4);
  285. end
  286. else
  287. begin
  288. System.Delete(Result, I, 1);
  289. end;
  290. end;
  291. Inc(I);
  292. end
  293. else
  294. Inc(I, 2);
  295. end;
  296. end;
  297. function EscapeAmpersands(const S: String): String;
  298. { Replaces any '&' characters with '&&' }
  299. var
  300. I: Integer;
  301. begin
  302. Result := S;
  303. I := 1;
  304. while I <= Length(Result) do begin
  305. if not CharInSet(Result[I], LeadBytes) then begin
  306. if Result[I] = '&' then begin
  307. Inc(I);
  308. Insert('&', Result, I);
  309. end;
  310. Inc(I);
  311. end
  312. else
  313. Inc(I, 2);
  314. end;
  315. end;
  316. function StripTrailingPunctuation(const S: String): String;
  317. { Removes any colon (':') or ellipsis ('...') from the end of S and returns
  318. the resulting string }
  319. var
  320. L: Integer;
  321. begin
  322. Result := S;
  323. L := Length(Result);
  324. if (L > 1) and (Result[L] = ':') and (ByteType(Result, L) = mbSingleByte) then
  325. SetLength(Result, L-1)
  326. else if (L > 3) and (Result[L-2] = '.') and (Result[L-1] = '.') and
  327. (Result[L] = '.') and (ByteType(Result, L-2) = mbSingleByte) then
  328. SetLength(Result, L-3);
  329. end;
  330. function GetTextWidth(const DC: HDC; S: String; const Prefix: Boolean): Integer;
  331. { Returns the width of the specified string using the font currently selected
  332. into DC. If Prefix is True, it first removes "&" characters as necessary. }
  333. var
  334. Size: TSize;
  335. begin
  336. { This procedure is 10x faster than using DrawText with the DT_CALCRECT flag }
  337. if Prefix then
  338. S := StripAccelChars(S);
  339. GetTextExtentPoint32(DC, PChar(S), Length(S), Size);
  340. Result := Size.cx;
  341. end;
  342. procedure ProcessPaintMessages;
  343. { Dispatches all pending WM_PAINT messages. In effect, this is like an
  344. 'UpdateWindow' on all visible windows }
  345. var
  346. Msg: TMsg;
  347. begin
  348. while PeekMessage(Msg, 0, WM_PAINT, WM_PAINT, PM_NOREMOVE) do begin
  349. case Integer(GetMessage(Msg, 0, WM_PAINT, WM_PAINT)) of
  350. -1: Break; { if GetMessage failed }
  351. 0: begin
  352. { Repost WM_QUIT messages }
  353. PostQuitMessage(Msg.WParam);
  354. Break;
  355. end;
  356. end;
  357. DispatchMessage(Msg);
  358. end;
  359. end;
  360. procedure RemoveMessages(const AMin, AMax: Integer);
  361. { Removes any messages with the specified ID from the queue }
  362. var
  363. Msg: TMsg;
  364. begin
  365. while PeekMessage(Msg, 0, AMin, AMax, PM_REMOVE) do begin
  366. if Msg.message = WM_QUIT then begin
  367. { Repost WM_QUIT messages }
  368. PostQuitMessage(Msg.WParam);
  369. Break;
  370. end;
  371. end;
  372. end;
  373. procedure SelectNCUpdateRgn(Wnd: HWND; DC: HDC; Rgn: HRGN);
  374. var
  375. R: TRect;
  376. NewClipRgn: HRGN;
  377. begin
  378. if (Rgn <> 0) and (Rgn <> 1) then begin
  379. GetWindowRect(Wnd, R);
  380. if SelectClipRgn(DC, Rgn) = ERROR then begin
  381. NewClipRgn := CreateRectRgnIndirect(R);
  382. SelectClipRgn(DC, NewClipRgn);
  383. DeleteObject(NewClipRgn);
  384. end;
  385. OffsetClipRgn(DC, -R.Left, -R.Top);
  386. end;
  387. end;
  388. function AddToList(var List: TList; Item: Pointer): Boolean;
  389. { Returns True if Item didn't already exist in the list }
  390. begin
  391. if List = nil then
  392. List := TList.Create;
  393. Result := List.IndexOf(Item) = -1;
  394. if Result then
  395. List.Add(Item);
  396. end;
  397. function AddToFrontOfList(var List: TList; Item: Pointer): Boolean;
  398. { Returns True if Item didn't already exist in the list }
  399. begin
  400. if List = nil then
  401. List := TList.Create;
  402. Result := List.IndexOf(Item) = -1;
  403. if Result then
  404. List.Insert(0, Item);
  405. end;
  406. procedure RemoveFromList(var List: TList; Item: Pointer);
  407. begin
  408. if Assigned(List) then begin
  409. List.Remove(Item);
  410. if List.Count = 0 then begin
  411. List.Free;
  412. List := nil;
  413. end;
  414. end;
  415. end;
  416. var
  417. RegMenuShowDelay: Integer;
  418. RegMenuShowDelayInited: BOOL = False;
  419. function GetMenuShowDelay: Integer;
  420. const
  421. DefaultMenuShowDelay = 400;
  422. function ReadMenuShowDelayFromRegistry: Integer;
  423. var
  424. K: HKEY;
  425. Typ, DataSize: DWORD;
  426. Data: array[0..31] of Char;
  427. Res: Longint;
  428. E: Integer;
  429. begin
  430. Result := DefaultMenuShowDelay;
  431. if RegOpenKeyEx(HKEY_CURRENT_USER, 'Control Panel\Desktop', 0,
  432. KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
  433. DataSize := SizeOf(Data);
  434. Res := RegQueryValueEx(K, 'MenuShowDelay', nil, @Typ, @Data, @DataSize);
  435. RegCloseKey(K);
  436. if Res <> ERROR_FILE_NOT_FOUND then begin
  437. if (Res <> ERROR_SUCCESS) or (Typ <> REG_SZ) then
  438. Result := 0
  439. else begin
  440. Val(Data, Result, E);
  441. if E <> 0 then Result := 0;
  442. end;
  443. end;
  444. end;
  445. end;
  446. begin
  447. if Lo(GetVersion) >= 4 then begin
  448. if not SystemParametersInfo(106{SPI_GETMENUSHOWDELAY}, 0, @Result, 0) then begin
  449. { SPI_GETMENUSHOWDELAY is only supported by Windows NT 4.0 and Windows 98.
  450. On Windows 95, it must use the registry to retrieve this setting. }
  451. if not RegMenuShowDelayInited then begin
  452. RegMenuShowDelay := ReadMenuShowDelayFromRegistry;
  453. InterlockedExchange(Integer(RegMenuShowDelayInited), Ord(True));
  454. end;
  455. Result := RegMenuShowDelay;
  456. end;
  457. if Result < 0 then Result := 0;
  458. end
  459. else
  460. Result := DefaultMenuShowDelay;
  461. end;
  462. function AreFlatMenusEnabled: Boolean;
  463. { Returns True if "flat menus" are enabled. Always returns False on pre-XP
  464. Windows versions. }
  465. const
  466. SPI_GETFLATMENU = $1022;
  467. var
  468. FlatMenusEnabled: BOOL;
  469. begin
  470. Result := SystemParametersInfo(SPI_GETFLATMENU, 0,
  471. @FlatMenusEnabled, 0) and FlatMenusEnabled;
  472. end;
  473. function AreKeyboardCuesEnabled: Boolean;
  474. { Returns True if "keyboard cues" are enabled. Always returns True on
  475. pre-2000 Windows versions. }
  476. const
  477. SPI_GETKEYBOARDCUES = $100A;
  478. var
  479. CuesEnabled: BOOL;
  480. begin
  481. Result :=
  482. not SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, @CuesEnabled, 0) or
  483. CuesEnabled;
  484. end;
  485. function CreateNullRegion: HRGN;
  486. var
  487. R: TRect;
  488. begin
  489. SetRectEmpty(R);
  490. Result := CreateRectRgnIndirect(R);
  491. end;
  492. procedure DrawInvertRect(const DC: HDC; const NewRect, OldRect: PRect;
  493. const NewSize, OldSize: TSize; const Brush: HBRUSH; BrushLast: HBRUSH);
  494. { Draws a dragging outline, hiding the old one if neccessary. This code is
  495. based on MFC sources.
  496. Either NewRect or OldRect can be nil or empty. }
  497. var
  498. SaveIndex: Integer;
  499. rgnNew, rgnOutside, rgnInside, rgnLast, rgnUpdate: HRGN;
  500. R: TRect;
  501. begin
  502. rgnLast := 0;
  503. rgnUpdate := 0;
  504. { First, determine the update region and select it }
  505. if NewRect = nil then begin
  506. SetRectEmpty(R);
  507. rgnOutside := CreateRectRgnIndirect(R);
  508. end
  509. else begin
  510. R := NewRect^;
  511. rgnOutside := CreateRectRgnIndirect(R);
  512. InflateRect(R, -NewSize.cx, -NewSize.cy);
  513. IntersectRect(R, R, NewRect^);
  514. end;
  515. rgnInside := CreateRectRgnIndirect(R);
  516. rgnNew := CreateNullRegion;
  517. CombineRgn(rgnNew, rgnOutside, rgnInside, RGN_XOR);
  518. if BrushLast = 0 then
  519. BrushLast := Brush;
  520. if OldRect <> nil then begin
  521. { Find difference between new region and old region }
  522. rgnLast := CreateNullRegion;
  523. with OldRect^ do
  524. SetRectRgn(rgnOutside, Left, Top, Right, Bottom);
  525. R := OldRect^;
  526. InflateRect(R, -OldSize.cx, -OldSize.cy);
  527. IntersectRect(R, R, OldRect^);
  528. SetRectRgn(rgnInside, R.Left, R.Top, R.Right, R.Bottom);
  529. CombineRgn(rgnLast, rgnOutside, rgnInside, RGN_XOR);
  530. { Only diff them if brushes are the same }
  531. if Brush = BrushLast then begin
  532. rgnUpdate := CreateNullRegion;
  533. CombineRgn(rgnUpdate, rgnLast, rgnNew, RGN_XOR);
  534. end;
  535. end;
  536. { Save the DC state so that the clipping region can be restored }
  537. SaveIndex := SaveDC(DC);
  538. try
  539. if (Brush <> BrushLast) and (OldRect <> nil) then begin
  540. { Brushes are different -- erase old region first }
  541. SelectClipRgn(DC, rgnLast);
  542. GetClipBox(DC, R);
  543. SelectObject(DC, BrushLast);
  544. PatBlt(DC, R.Left, R.Top, R.Right-R.Left, R.Bottom-R.Top, PATINVERT);
  545. end;
  546. { Draw into the update/new region }
  547. if rgnUpdate <> 0 then
  548. SelectClipRgn(DC, rgnUpdate)
  549. else
  550. SelectClipRgn(DC, rgnNew);
  551. GetClipBox(DC, R);
  552. SelectObject(DC, Brush);
  553. PatBlt(DC, R.Left, R.Top, R.Right-R.Left, R.Bottom-R.Top, PATINVERT);
  554. finally
  555. { Clean up DC }
  556. RestoreDC(DC, SaveIndex);
  557. end;
  558. { Free regions }
  559. if rgnNew <> 0 then DeleteObject(rgnNew);
  560. if rgnOutside <> 0 then DeleteObject(rgnOutside);
  561. if rgnInside <> 0 then DeleteObject(rgnInside);
  562. if rgnLast <> 0 then DeleteObject(rgnLast);
  563. if rgnUpdate <> 0 then DeleteObject(rgnUpdate);
  564. end;
  565. function CreateHalftoneBrush: HBRUSH;
  566. const
  567. Patterns: array[Boolean] of Word = ($5555, $AAAA);
  568. var
  569. I: Integer;
  570. GrayPattern: array[0..7] of Word;
  571. GrayBitmap: HBITMAP;
  572. begin
  573. for I := 0 to 7 do
  574. GrayPattern[I] := Patterns[Odd(I)];
  575. GrayBitmap := CreateBitmap(8, 8, 1, 1, @GrayPattern);
  576. Result := CreatePatternBrush(GrayBitmap);
  577. DeleteObject(GrayBitmap);
  578. end;
  579. procedure DrawHalftoneInvertRect(const DC: HDC; const NewRect, OldRect: PRect;
  580. const NewSize, OldSize: TSize);
  581. var
  582. Brush: HBRUSH;
  583. begin
  584. Brush := CreateHalftoneBrush;
  585. try
  586. DrawInvertRect(DC, NewRect, OldRect, NewSize, OldSize, Brush, Brush);
  587. finally
  588. DeleteObject(Brush);
  589. end;
  590. end;
  591. function MethodsEqual(const M1, M2: TMethod): Boolean;
  592. begin
  593. Result := (M1.Code = M2.Code) and (M1.Data = M2.Data);
  594. end;
  595. function GetRectOfPrimaryMonitor(const WorkArea: Boolean): TRect;
  596. begin
  597. if not WorkArea or not SystemParametersInfo(SPI_GETWORKAREA, 0, @Result, 0) then
  598. Result := Rect(0, 0, Screen.Width, Screen.Height);
  599. end;
  600. function UsingMultipleMonitors: Boolean;
  601. { Returns True if the system has more than one display monitor configured. }
  602. var
  603. NumMonitors: Integer;
  604. begin
  605. NumMonitors := GetSystemMetrics(80 {SM_CMONITORS});
  606. Result := (NumMonitors <> 0) and (NumMonitors <> 1);
  607. { ^ NumMonitors will be zero if not running Win98, NT 5, or later }
  608. end;
  609. type
  610. HMONITOR = type Integer;
  611. PMonitorInfo = ^TMonitorInfo;
  612. TMonitorInfo = record
  613. cbSize: DWORD;
  614. rcMonitor: TRect;
  615. rcWork: TRect;
  616. dwFlags: DWORD;
  617. end;
  618. const
  619. MONITOR_DEFAULTTONEAREST = $2;
  620. type
  621. TMultiMonApis = record
  622. funcMonitorFromRect: function(lprcScreenCoords: PRect; dwFlags: DWORD): HMONITOR; stdcall;
  623. funcMonitorFromPoint: function(ptScreenCoords: TPoint; dwFlags: DWORD): HMONITOR; stdcall;
  624. funcMonitorFromWindow: function(hWnd: HWND; dwFlags: DWORD): HMONITOR; stdcall;
  625. funcGetMonitorInfoW: function(hMonitor: HMONITOR; lpMonitorInfo: PMonitorInfo): BOOL; stdcall;
  626. end;
  627. { Under D4 I could be using the MultiMon unit for the multiple monitor
  628. function imports, but its stubs for MonitorFromRect and MonitorFromPoint
  629. are seriously bugged... So I chose to avoid the MultiMon unit entirely. }
  630. function InitMultiMonApis(var Apis: TMultiMonApis): Boolean;
  631. var
  632. User32Handle: THandle;
  633. begin
  634. User32Handle := GetModuleHandle(user32);
  635. Apis.funcMonitorFromRect := GetProcAddress(User32Handle, 'MonitorFromRect');
  636. Apis.funcMonitorFromPoint := GetProcAddress(User32Handle, 'MonitorFromPoint');
  637. Apis.funcMonitorFromWindow := GetProcAddress(User32Handle, 'MonitorFromWindow');
  638. Apis.funcGetMonitorInfoW := GetProcAddress(User32Handle, 'GetMonitorInfoW');
  639. Result := Assigned(Apis.funcMonitorFromRect) and
  640. Assigned(Apis.funcMonitorFromPoint) and Assigned(Apis.funcGetMonitorInfoW);
  641. end;
  642. function GetRectOfMonitorContainingRect(const R: TRect;
  643. const WorkArea: Boolean): TRect;
  644. { Returns the work area of the monitor which the rectangle R intersects with
  645. the most, or the monitor nearest R if no monitors intersect. }
  646. var
  647. Apis: TMultiMonApis;
  648. M: HMONITOR;
  649. MonitorInfo: TMonitorInfo;
  650. begin
  651. if UsingMultipleMonitors and InitMultiMonApis(Apis) then begin
  652. M := Apis.funcMonitorFromRect(@R, MONITOR_DEFAULTTONEAREST);
  653. MonitorInfo.cbSize := SizeOf(MonitorInfo);
  654. if Apis.funcGetMonitorInfoW(M, @MonitorInfo) then begin
  655. if not WorkArea then
  656. Result := MonitorInfo.rcMonitor
  657. else
  658. Result := MonitorInfo.rcWork;
  659. Exit;
  660. end;
  661. end;
  662. Result := GetRectOfPrimaryMonitor(WorkArea);
  663. end;
  664. function GetRectOfMonitorContainingPoint(const P: TPoint;
  665. const WorkArea: Boolean): TRect;
  666. { Returns the screen area of the monitor containing the point P, or the monitor
  667. nearest P if P isn't in any monitor's work area. }
  668. var
  669. Apis: TMultiMonApis;
  670. M: HMONITOR;
  671. MonitorInfo: TMonitorInfo;
  672. begin
  673. if UsingMultipleMonitors and InitMultiMonApis(Apis) then begin
  674. M := Apis.funcMonitorFromPoint(P, MONITOR_DEFAULTTONEAREST);
  675. MonitorInfo.cbSize := SizeOf(MonitorInfo);
  676. if Apis.funcGetMonitorInfoW(M, @MonitorInfo) then begin
  677. if not WorkArea then
  678. Result := MonitorInfo.rcMonitor
  679. else
  680. Result := MonitorInfo.rcWork;
  681. Exit;
  682. end;
  683. end;
  684. Result := GetRectOfPrimaryMonitor(WorkArea);
  685. end;
  686. function GetRectOfMonitorContainingWindow(const W: HWND;
  687. const WorkArea: Boolean): TRect;
  688. var
  689. Apis: TMultiMonApis;
  690. M: HMONITOR;
  691. MonitorInfo: TMonitorInfo;
  692. begin
  693. if UsingMultipleMonitors and InitMultiMonApis(Apis) then begin
  694. M := Apis.funcMonitorFromWindow(W, MONITOR_DEFAULTTONEAREST);
  695. MonitorInfo.cbSize := SizeOf(MonitorInfo);
  696. if Apis.funcGetMonitorInfoW(M, @MonitorInfo) then begin
  697. if not WorkArea then
  698. Result := MonitorInfo.rcMonitor
  699. else
  700. Result := MonitorInfo.rcWork;
  701. Exit;
  702. end;
  703. end;
  704. Result := GetRectOfPrimaryMonitor(WorkArea);
  705. end;
  706. function CallTrackMouseEvent(const Wnd: HWND; const Flags: DWORD): Boolean;
  707. var
  708. Track: TTrackMouseEvent;
  709. begin
  710. Track.cbSize := SizeOf(Track);
  711. Track.dwFlags := Flags;
  712. Track.hwndTrack := Wnd;
  713. Track.dwHoverTime := 0;
  714. Result := TrackMouseEvent(Track);
  715. end;
  716. function EnumFontsProc(const lplf: TLogFont; const lptm: TTextMetric;
  717. dwType: DWORD; lpData: LPARAM): Integer; stdcall;
  718. begin
  719. Boolean(Pointer(lpData)^) := True;
  720. Result := 0;
  721. end;
  722. function CreateRotatedFont(DC: HDC): HFONT;
  723. { Creates a font based on the DC's current font, but rotated 270 degrees }
  724. var
  725. LogFont: TLogFont;
  726. TM: TTextMetric;
  727. VerticalFontName: array[0..LF_FACESIZE-1] of Char;
  728. VerticalFontExists: Boolean;
  729. begin
  730. if GetObject(GetCurrentObject(DC, OBJ_FONT), SizeOf(LogFont),
  731. @LogFont) = 0 then begin
  732. { just in case... }
  733. Result := 0;
  734. Exit;
  735. end;
  736. LogFont.lfEscapement := 2700;
  737. LogFont.lfOrientation := 2700;
  738. LogFont.lfOutPrecision := OUT_TT_ONLY_PRECIS; { needed for Win9x }
  739. { Don't let a random TrueType font be substituted when MS Sans Serif or
  740. Microsoft Sans Serif are used. Hard-code Arial. }
  741. if (StrIComp(LogFont.lfFaceName, 'MS Sans Serif') = 0) or
  742. (StrIComp(LogFont.lfFaceName, 'Microsoft Sans Serif') = 0) then begin
  743. StrPCopy(LogFont.lfFaceName, 'Arial');
  744. { Set lfHeight to the actual height of the current font. This is needed
  745. to work around a Windows 98 issue: on a clean install of the OS,
  746. SPI_GETNONCLIENTMETRICS returns -5 for lfSmCaptionFont.lfHeight. This is
  747. wrong; it should return -11 for an 8 pt font. With normal, unrotated text
  748. this actually displays correctly, since MS Sans Serif doesn't support
  749. sizes below 8 pt. However, when we change to a TrueType font like Arial,
  750. this becomes a problem because it'll actually create a font that small. }
  751. if GetTextMetrics(DC, TM) then begin
  752. { If the original height was negative, keep it negative }
  753. if LogFont.lfHeight <= 0 then
  754. LogFont.lfHeight := -(TM.tmHeight - TM.tmInternalLeading)
  755. else
  756. LogFont.lfHeight := TM.tmHeight;
  757. end;
  758. end;
  759. { Use a vertical font if available so that Asian characters aren't drawn
  760. sideways }
  761. if StrLen(LogFont.lfFaceName) < SizeOf(VerticalFontName)-1 then begin
  762. VerticalFontName[0] := '@';
  763. StrCopy(@VerticalFontName[1], LogFont.lfFaceName);
  764. VerticalFontExists := False;
  765. EnumFonts(DC, VerticalFontName, @EnumFontsProc, @VerticalFontExists);
  766. if VerticalFontExists then
  767. StrCopy(LogFont.lfFaceName, VerticalFontName);
  768. end;
  769. Result := CreateFontIndirect(LogFont);
  770. end;
  771. procedure DrawRotatedText(const DC: HDC; AText: String; const ARect: TRect;
  772. const AFormat: Cardinal);
  773. { Like DrawText, but draws the text at a 270 degree angle.
  774. The format flag this function respects are
  775. DT_NOPREFIX, DT_HIDEPREFIX, DT_CENTER, DT_END_ELLIPSIS, DT_NOCLIP }
  776. var
  777. RotatedFont, SaveFont: HFONT;
  778. TextMetrics: TTextMetric;
  779. X, Y, P, I, SU, FU, W: Integer;
  780. SaveAlign: UINT;
  781. SavePen, Pen: HPEN;
  782. Clip: Boolean;
  783. function GetSize(DC: HDC; const S: string): Integer;
  784. var
  785. Size: TSize;
  786. begin
  787. GetTextExtentPoint32(DC, PChar(S), Length(S), Size);
  788. Result := Size.cx;
  789. end;
  790. begin
  791. if Length(AText) = 0 then Exit;
  792. RotatedFont := CreateRotatedFont(DC);
  793. SaveFont := SelectObject(DC, RotatedFont);
  794. GetTextMetrics(DC, TextMetrics);
  795. X := ARect.Left + ((ARect.Right - ARect.Left) - TextMetrics.tmHeight) div 2;
  796. Clip := (AFormat and DT_NOCLIP) <> DT_NOCLIP;
  797. { Find the index of the character that should be underlined. Delete '&'
  798. characters from the string. Like DrawText, only the last prefixed character
  799. will be underlined. }
  800. P := 0;
  801. I := 1;
  802. if (AFormat and DT_NOPREFIX) <> DT_NOPREFIX then
  803. while I <= Length(AText) do begin
  804. if CharInSet(AText[I], LeadBytes) then
  805. Inc(I)
  806. else if AText[I] = '&' then begin
  807. Delete(AText, I, 1);
  808. { Note: PChar cast is so that if Delete deleted the last character in
  809. the string, we don't step past the end of the string (which would cause
  810. an AV if AText is now empty), but rather look at the null character
  811. and treat it as an accelerator key like DrawText. }
  812. if PChar(AText)[I-1] <> '&' then
  813. P := I;
  814. end;
  815. Inc(I);
  816. end;
  817. if (AFormat and DT_END_ELLIPSIS) = DT_END_ELLIPSIS then
  818. begin
  819. if (Length(AText) > 1) and (GetSize(DC, AText) > ARect.Bottom - ARect.Top) then
  820. begin
  821. W := ARect.Bottom - ARect.Top;
  822. if W > 2 then
  823. begin
  824. Delete(AText, Length(AText), 1);
  825. while (Length(AText) > 1) and (GetSize(DC, AText + '...') > W) do
  826. Delete(AText, Length(AText), 1);
  827. end
  828. else AText := AText[1];
  829. if P > Length(AText) then P := 0;
  830. AText := AText + '...';
  831. end;
  832. end;
  833. if (AFormat and DT_CENTER) = DT_CENTER then
  834. Y := ARect.Top + ((ARect.Bottom - ARect.Top) - GetSize(DC, AText)) div 2
  835. else
  836. Y := ARect.Top;
  837. if Clip then
  838. begin
  839. SaveDC(DC);
  840. with ARect do IntersectClipRect(DC, Left, Top, Right, Bottom);
  841. end;
  842. SaveAlign := SetTextAlign(DC, TA_BOTTOM);
  843. TextOut(DC, X, Y, PChar(AText), Length(AText));
  844. SetTextAlign(DC, SaveAlign);
  845. { Underline }
  846. if (P > 0) and (AFormat and DT_HIDEPREFIX = 0) then begin
  847. SU := GetTextWidth(DC, Copy(AText, 1, P-1), False);
  848. FU := SU + GetTextWidth(DC, PChar(AText)[P-1], False);
  849. Inc(X, TextMetrics.tmDescent - 2);
  850. Pen := CreatePen(PS_SOLID, 1, GetTextColor(DC));
  851. SavePen := SelectObject(DC, Pen);
  852. MoveToEx(DC, X, Y + SU, nil);
  853. LineTo(DC, X, Y + FU);
  854. SelectObject(DC, SavePen);
  855. DeleteObject(Pen);
  856. end;
  857. if Clip then RestoreDC(DC, -1);
  858. SelectObject(DC, SaveFont);
  859. DeleteObject(RotatedFont);
  860. end;
  861. function NeedToPlaySound(const Alias: String): Boolean;
  862. { This function checks the registry to see if the specified sound event alias
  863. is assigned to a file.
  864. The purpose of having this function is so it can avoid calls to PlaySound if
  865. possible, because on Windows 2000 there is an annoying 1/3 second delay on
  866. the first call to PlaySound.
  867. Windows Explorer actually uses this same technique when playing sounds for
  868. the Start menu. }
  869. var
  870. K: HKEY;
  871. Data: array[0..3] of WideChar;
  872. DataSize: DWORD;
  873. ErrorCode: Longint;
  874. begin
  875. Result := False;
  876. if RegOpenKeyEx(HKEY_CURRENT_USER,
  877. PChar('AppEvents\Schemes\Apps\.Default\' + Alias + '\.Current'),
  878. 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin
  879. DataSize := SizeOf(Data);
  880. { Note: Use the 'W' version of RegQueryValueEx for more speed }
  881. ErrorCode := RegQueryValueExW(K, nil, nil, nil, @Data, @DataSize);
  882. if ((ErrorCode = ERROR_SUCCESS) and (Data[0] <> #0)) or
  883. (ErrorCode = ERROR_MORE_DATA) then
  884. Result := True;
  885. RegCloseKey(K);
  886. end;
  887. end;
  888. function Max(A, B: Integer): Integer;
  889. begin
  890. if A >= B then
  891. Result := A
  892. else
  893. Result := B;
  894. end;
  895. function Min(A, B: Integer): Integer;
  896. begin
  897. if A <= B then
  898. Result := A
  899. else
  900. Result := B;
  901. end;
  902. function FindAccelChar(const S: String): Char;
  903. { Finds the last accelerator key in S. Returns #0 if no accelerator key was
  904. found. '&&' is ignored. }
  905. var
  906. P: PChar;
  907. begin
  908. P := PChar(S);
  909. Result := #0;
  910. while True do begin
  911. P := AnsiStrScan(P, '&');
  912. if P = nil then Break;
  913. Inc(P);
  914. if P^ <> '&' then begin
  915. if P^ = #0 then Break;
  916. Result := P^;
  917. end;
  918. Inc(P);
  919. end;
  920. end;
  921. function GetInputLocaleCodePage: UINT;
  922. { Returns the code page identifier of the active input locale, or CP_ACP if
  923. for some unknown reason it couldn't be determined. }
  924. var
  925. Buf: array[0..15] of Char;
  926. ErrorCode: Integer;
  927. begin
  928. if GetLocaleInfo(GetKeyboardLayout(0) and $FFFF, LOCALE_IDEFAULTANSICODEPAGE,
  929. Buf, SizeOf(Buf)) > 0 then begin
  930. Buf[High(Buf)] := #0; { ensure null termination, just in case... }
  931. Val(Buf, Result, ErrorCode);
  932. { Just to be *completely* safe, verify that the code page returned by
  933. GetLocaleInfo actually exists. The result of this function may be fed
  934. into WideCharToMultiByte, and we don't want WideCharToMultiByte to fail
  935. entirely because of a bad code page. }
  936. if (ErrorCode <> 0) or not IsValidCodePage(Result) then
  937. Result := CP_ACP;
  938. end
  939. else
  940. Result := CP_ACP;
  941. end;
  942. end.