FireMonkey/Rad Studio XE2: How can I show the SaveDialog filter on OS X? [duplicate] - macos

I created an (Delphi XE2) Firemonkey sample program which contains a TButton and a TSavedialog with two different filters.
(The TSaveDialog component supports the Win32/Win64 and OS X platform.)
It works fine on Win32/Win64, but I don't now why it does not show the Savedialog filters on OS X (VirtualBox/OS X 10.7.x).
How can I get it to work on OS X ?
procedure TForm1.Button_SaveClick(Sender: TObject);
begin
SaveDialog.Filter:='Format_1 (*.fmt1)|*.fmt1|Format_2 (*.fmt2)|*.fmt2';
If Savedialog.Execute Then ShowMessage(SaveDialog.FileName+#13+'Selected filterindex: '+Inttostr(SaveDialog.FilterIndex));
end;

The Save dialog is not constructed in Delphi but calls the native MAC OSX dialog (NSSavePanel). This does not have a user selectable filter.
When you execute a save dialog, Delphi passes the filter as an array to NSSavePanel.SetAllowedFileTypes which determines what extensions the OSX dialog will allow the user to specify - but there is no selectable list.
To allow the user to select from a list, you would need to create your own filetype selection dialog box and then take that selection and pass to the savedialog as the default file type and the only filter item.
The alternative of creating a completely new fileSave dialog is not easy as the Firemonkey tree component seems to insist on expanding all its nodes and hence performs a complete traverse of all the files on your hard drive. In any case, MAC users will be familiar with the standard dialog.

I had got the same problem with TOpendialog in MAC OSX: filter don't work, but in Windows they do. Now I solved the problem, perhaps you can use the code for your workaround. Those files which are NOT displayed in Windows are disabled under MAC OSX, you cannot select them.
uses
Macapi.Foundation, Macapi.ObjectiveC, Macapi.AppKit;
{$IFDEF MACOS}
function AllocFilterStr(const S: string; var Filter: NSArray): Boolean;
var
input, pattern: string;
FileTypes: array of string;
outcome, aux: TArray<string>;
i, j: Integer;
FileTypesNS: array of Pointer;
NStr: NSString;
LocObj: ILocalObject;
begin
// First, split the string by using '|' as a separator
Result := false;
input := S;
pattern := '\|';
outcome := TRegEx.Split(input, pattern);
pattern := '\*\.';
SetLength(FileTypes, 0);
for i := 0 to length(outcome) - 1 do
begin
if Odd(i) then
if outcome[i] <> '*.*' then
if AnsiLeftStr(outcome[i], 2) = '*.' then
begin
aux := TRegEx.Split(outcome[i], pattern);
for j := 0 to length(aux) - 1 do
begin
aux[j] := Trim(aux[j]);
if aux[j] <> '' then
begin
if AnsiEndsStr(';', aux[j]) then
aux[j] := AnsiLeftStr(aux[j], length(aux[j]) - 1);
SetLength(FileTypes, length(FileTypes) + 1);
FileTypes[length(FileTypes) - 1] := aux[j];
end;
end;
end;
end;
// create the NSArray from the FileTypes array
SetLength(FileTypesNS, length(FileTypes));
for i := 0 to length(FileTypes) - 1 do
begin
NStr := NSSTR(FileTypes[i]);
if Supports(NStr, ILocalObject, LocObj) then
FileTypesNS[i] := LocObj.GetObjectID;
end;
if length(FileTypes) > 0 then begin
Filter := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(#FileTypesNS[0], length(FileTypes)));
result := true;
end;
end;
function CFToDelphiString(const CFStr: CFStringRef): string;
var
Range: CFRange;
begin
Range.location := 0;
Range.length := CFStringGetLength(CFStr);
SetLength(Result, Range.length);
if Range.length = 0 then Exit;
CFStringGetCharacters(CFStr, Range, PWideChar(Result));
end;
function NSToDelphiString(const NSStr: NSString): string; inline;
begin
Result := CFToDelphiString((NSStr as ILocalObject).GetObjectID);
end;
{$ENDIF}
procedure TMainform.LoadClick(Sender: TObject);
{$IFDEF MACOS}
var
Filter: NSArray;
LOpenDir: NSOpenPanel;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
Opendialog1.Filter:= '*.fcb|*.fcb';
if Opendialog1.execute then
begin
case Opendialog1.Filterindex of
1: LoadPlaylist(Opendialog1.filename, false, false);
2: LoadPlaylist(Opendialog1.filename, false, true);
end;
end;
{$ENDIF}
{$IFDEF MACOS}
LOpenDir := TNSOpenPanel.Wrap(TNSOpenPanel.OCClass.openPanel);
if AllocFilterStr('*.fcb|*.fcb', Filter) then
if LOpenDir.runModalForTypes(Filter)=1 then
LoadPlaylist(NSToDelphiString(LOpenDir.filename), false, false);
{$ENDIF}
end;

Related

Find HID/PID in DELPHI / ARDUINO Interface

(First, I am not sure whether this question is placed in the correct section of Stack Exchange. If not so, please give me a notice and delete the question.)
I have 8 Arduino's (Ards). Some Uno's and some 2650 Mega's. In an attempt to automatize the connection process (I use Delphi D-7 SE as I/O), I want to differentate between the UNO and the 2650 (mostly because the hardware differences in the appropriate chip). The way to do this (I think), is to get the PID and VID from the board. But I don't know how to do this. The code below gives me the correct driver, but not PID/VID . Is it possible to get PID/VID for this code-snippet ?? IF so, HOW ?
Thanks a lot.
Code here:
unit ArduinoTestU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, JVsetupAPI, Registry, StdCtrls,
CPortCtl, CPort, Menus, XPMan;
type
TMainForm = class(TForm)
ListBox1: TListBox;
Label1: TLabel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
function SetupEnumAvailableComPorts : TstringList;
procedure ListBox1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
ArdType : Integer;
end;
var
MainForm : TMainForm;
ComPortStringList : TStringList;
MyComPort : String;
CurDir : String;
implementation
uses Form1Unit, ArdFormU; (* , ArdFormU; *)
{$R *.dfm}
procedure TMainForm.Button1Click(Sender: TObject);
begin
MainForm.FormActivate(NIL);
end;
procedure TMainForm.FormActivate(Sender: TObject);
var
index : integer;
begin
ComPortStringList := SetupEnumAvailableComPorts;
if (ComPortStringList <> nil) and (ComPortStringList.Count > 0) then
for Index := 0 to ComPortStringList.Count - 1 do
Listbox1.Items.Add(ComPortStringList[Index]);
if Listbox1.Items.Count <> 0 then
BEGIN
Listbox1.Enabled := True;
Button1.Enabled := False;
END;
end;
procedure TMainForm.FormCreate(Sender: TObject);
BEGIN
Curdir := ExtractFileDir(Application.Exename);
end;
(*
The function below returns a list of available COM-ports
(not open by this or an other process), with friendly names. The list is formatted as follows:
COM1: = Communications Port (COM1)
COM5: = NI Serial Port (Com5)
COM6: = NI Serial Port (Com6)
COM7: = USB Serial Port (COM7)
COM8: = Bluetooth Communications Port (COM8)
COM9: = Bluetooth Communications Port (COM9)
This code originally posted at http://www.delphi3000.com/articles/article_4001.asp?SK=
errors have been fixed so it will work with Delphi 7 and SetupAPI from JVCL
*)
function TMainForm.SetupEnumAvailableComPorts : TstringList;
//
// Enumerates all serial communications ports that are available and ready to
// be used.
//
var
RequiredSize: Cardinal;
GUIDSize: DWORD;
Guid: TGUID;
DevInfoHandle: HDEVINFO;
DeviceInfoData: TSPDevInfoData;
MemberIndex: Cardinal;
PropertyRegDataType: DWord;
RegProperty: Cardinal;
RegTyp: Cardinal;
Key: Hkey;
Info: TRegKeyInfo;
S1,S2: string;
hc: THandle;
begin
Result := Nil;
//
//If we cannot access the setupapi.dll then we return a nil pointer.
//
if not LoadsetupAPI then
exit;
try
//
// get 'Ports' class guid from name
//
GUIDSize := 1; // missing from original code - need to tell function that the Guid structure contains a single GUID
if SetupDiClassGuidsFromName('Ports',#Guid,GUIDSize,RequiredSize) then
begin
//
//get object handle of 'Ports' class to interate all devices
//
DevInfoHandle := SetupDiGetClassDevs(#Guid,Nil,0,DIGCF_PRESENT);
if Cardinal(DevInfoHandle) <> Invalid_Handle_Value then
begin
try
MemberIndex := 0;
result := TStringList.Create;
//iterate device list
repeat
FillChar(DeviceInfoData,SizeOf(DeviceInfoData),0);
DeviceInfoData.cbSize := SizeOf(DeviceInfoData);
//get device info that corresponds to the next memberindex
if Not SetupDiEnumDeviceInfo(DevInfoHandle,MemberIndex,DeviceInfoData) then
break;
//query friendly device name LIKE 'BlueTooth Communication Port (COM8)' etc
RegProperty := SPDRP_FriendlyName; {SPDRP_Driver, SPDRP_SERVICE, SPDRP_ENUMERATOR_NAME,SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,SPDRP_FRIENDLYNAME,}
SetupDiGetDeviceRegistryProperty(DevInfoHandle, DeviceInfoData,RegProperty, PropertyRegDataType,NIL,0,RequiredSize);
SetLength(S1,RequiredSize);
// ShowMessage('TEST: ' + S1);
if SetupDiGetDeviceRegistryProperty(DevInfoHandle,DeviceInfoData,RegProperty,PropertyRegDataType,#S1[1],RequiredSize,RequiredSize) then
begin
KEY := SetupDiOpenDevRegKey(DevInfoHandle,DeviceInfoData,DICS_FLAG_GLOBAL,0,DIREG_DEV,KEY_READ);
if key <> INValid_Handle_Value then
begin
FillChar(Info, SizeOf(Info), 0);
//query the real port name from the registry value 'PortName'
if RegQueryInfoKey(Key, nil, nil, nil, #Info.NumSubKeys,#Info.MaxSubKeyLen, nil, #Info.NumValues, #Info.MaxValueLen,
#Info.MaxDataLen, nil, #Info.FileTime) = ERROR_SUCCESS then
begin
RequiredSize := Info.MaxValueLen + 1;
SetLength(S2,RequiredSize);
if RegQueryValueEx(KEY,'PortName',Nil,#Regtyp,#s2[1],#RequiredSize) = Error_Success then
begin
If (Pos('COM',S2) = 1) then
begin
//Test if the device can be used
hc := CreateFile(pchar('\\.\' + S2 + #0), GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if hc <> INVALID_HANDLE_VALUE then
begin
Result.Add(Strpas(PChar(S2)) + ' := ' + StrPas(PChar(S1)));
CloseHandle(hc);
end;
end;
end;
end;
RegCloseKey(key);
end;
end;
Inc(MemberIndex);
until False;
//If we did not found any free com. port we return a NIL pointer.
if Result.Count = 0 then
begin
Result.Free;
Result := NIL;
end
finally
SetupDiDestroyDeviceInfoList(DevInfoHandle);
end;
end;
end;
finally
UnloadSetupApi;
end;
end;
procedure TMainForm.ListBox1Click(Sender: TObject);
begin
Ardtype := Listbox1.ItemIndex;
MainForm.Hide;
ArdForm.ShowModal;
if Ardform.ModalResult <> mrOK then
ShowMessage('Der opstod en fejl ')
ELSE
BEGIN
MainForm.Show;
END;
end;
end.
Kris aka snestrup2016

How to avoid flickering when animating GUI components in Lazarus

I'm moving a TMemo object left and right in my GUI application. The problem is, is that the letters in my TMemo are flickering as soon as the movement starts.
I've looked this up, and, apparently, setting the DoubleBuffering property of my main form should've helped me, but it didn't. So I tried setting that property to true on all objects that were moving, but flickering was still present.
Are there any ways to achieve flicker-free animations of GUI components in Lazarus? I'm a novice in Lazarus, so I'm kind of blindly googling for solutions right now. I would really appreciate some help.
To provide further context, here's how I animate my TMemo: I've got a TTimer with an interval value of 10, and its OnTimer event moves my TMemo left and right contiguously. To make the movement slightly smoother, I added a simple cosine interpolation function.
In the end here's the code:
procedure TServerSideForm.ControlPanelHideTimerTimer(Sender: TObject);
begin
if (hideAnimVal < 1) then
begin
hideAnimVal := hideAnimVal + 0.025;
end
else
begin
MemoHideTimer.Enabled:=false;
end;
// hideStart - starting position of my TMemo, hideEnd - end position of my TMemo
hideCurr := Round(CosineInterpolation(hideStart, hideEnd, hideAnimVal));
Memo.Left:=hideCurr;
end;
Cosine interpolation:
function CosineInterpolation(Val1, Val2, Angle: Double): Double;
var
Percent: Double;
begin
Percent := (1-Cos(Angle*PI))/2;
Result := (Val1 * (1 - Percent) + Val2 * Percent);
end;
I would try to move an image instead:
var
Memo1dc: hdc;
Cnv: TCanvas;
Rct: TRect;
implementation
procedure TForm1.MemoHideTimerTimer(Sender: TObject);
begin
if Memo1.Visible then
begin
Memo1dc := GetDC(Memo1.Handle);
Cnv.Handle := Memo1dc;
Rct.Height := Memo1.Height;
Rct.Width := Memo1.Width;
Image1.Left := Memo1.Left;
Image1.Top := Memo1.Top;
Image1.Width := Memo1.Width;
Image1.Height := Memo1.Height;
Image1.Canvas.CopyRect(Rct, Cnv, Rct);
Memo1.Visible := False;
Image1.Visible := True;
end;
if (hideAnimVal < 1) then
begin
hideAnimVal := hideAnimVal + 0.025;
end
else
begin
MemoHideTimer.Enabled := False;
end;
// hideStart - starting position of my TMemo, hideEnd - end position of my TMemo
hideCurr := Round(CosineInterpolation(hideStart, hideEnd, hideAnimVal));
Image1.Left := hideCurr;
if MemoHideTimer.Enabled = False then
begin
Memo1.Left := Image1.Left;
Memo1.Visible := True;
Image1.Visible := False;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Cnv := TCanvas.Create;
end;

FireMonkey/Rad Studio XE2: How can I show the SaveDialog filter on OS X?

I created an (Delphi XE2) Firemonkey sample program which contains a TButton and a TSavedialog with two different filters.
(The TSaveDialog component supports the Win32/Win64 and OS X platform.)
It works fine on Win32/Win64, but I don't now why it does not show the Savedialog filters on OS X (VirtualBox/OS X 10.7.x).
How can I get it to work on OS X ?
procedure TForm1.Button_SaveClick(Sender: TObject);
begin
SaveDialog.Filter:='Format_1 (*.fmt1)|*.fmt1|Format_2 (*.fmt2)|*.fmt2';
If Savedialog.Execute Then ShowMessage(SaveDialog.FileName+#13+'Selected filterindex: '+Inttostr(SaveDialog.FilterIndex));
end;
The Save dialog is not constructed in Delphi but calls the native MAC OSX dialog (NSSavePanel). This does not have a user selectable filter.
When you execute a save dialog, Delphi passes the filter as an array to NSSavePanel.SetAllowedFileTypes which determines what extensions the OSX dialog will allow the user to specify - but there is no selectable list.
To allow the user to select from a list, you would need to create your own filetype selection dialog box and then take that selection and pass to the savedialog as the default file type and the only filter item.
The alternative of creating a completely new fileSave dialog is not easy as the Firemonkey tree component seems to insist on expanding all its nodes and hence performs a complete traverse of all the files on your hard drive. In any case, MAC users will be familiar with the standard dialog.
I had got the same problem with TOpendialog in MAC OSX: filter don't work, but in Windows they do. Now I solved the problem, perhaps you can use the code for your workaround. Those files which are NOT displayed in Windows are disabled under MAC OSX, you cannot select them.
uses
Macapi.Foundation, Macapi.ObjectiveC, Macapi.AppKit;
{$IFDEF MACOS}
function AllocFilterStr(const S: string; var Filter: NSArray): Boolean;
var
input, pattern: string;
FileTypes: array of string;
outcome, aux: TArray<string>;
i, j: Integer;
FileTypesNS: array of Pointer;
NStr: NSString;
LocObj: ILocalObject;
begin
// First, split the string by using '|' as a separator
Result := false;
input := S;
pattern := '\|';
outcome := TRegEx.Split(input, pattern);
pattern := '\*\.';
SetLength(FileTypes, 0);
for i := 0 to length(outcome) - 1 do
begin
if Odd(i) then
if outcome[i] <> '*.*' then
if AnsiLeftStr(outcome[i], 2) = '*.' then
begin
aux := TRegEx.Split(outcome[i], pattern);
for j := 0 to length(aux) - 1 do
begin
aux[j] := Trim(aux[j]);
if aux[j] <> '' then
begin
if AnsiEndsStr(';', aux[j]) then
aux[j] := AnsiLeftStr(aux[j], length(aux[j]) - 1);
SetLength(FileTypes, length(FileTypes) + 1);
FileTypes[length(FileTypes) - 1] := aux[j];
end;
end;
end;
end;
// create the NSArray from the FileTypes array
SetLength(FileTypesNS, length(FileTypes));
for i := 0 to length(FileTypes) - 1 do
begin
NStr := NSSTR(FileTypes[i]);
if Supports(NStr, ILocalObject, LocObj) then
FileTypesNS[i] := LocObj.GetObjectID;
end;
if length(FileTypes) > 0 then begin
Filter := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(#FileTypesNS[0], length(FileTypes)));
result := true;
end;
end;
function CFToDelphiString(const CFStr: CFStringRef): string;
var
Range: CFRange;
begin
Range.location := 0;
Range.length := CFStringGetLength(CFStr);
SetLength(Result, Range.length);
if Range.length = 0 then Exit;
CFStringGetCharacters(CFStr, Range, PWideChar(Result));
end;
function NSToDelphiString(const NSStr: NSString): string; inline;
begin
Result := CFToDelphiString((NSStr as ILocalObject).GetObjectID);
end;
{$ENDIF}
procedure TMainform.LoadClick(Sender: TObject);
{$IFDEF MACOS}
var
Filter: NSArray;
LOpenDir: NSOpenPanel;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
Opendialog1.Filter:= '*.fcb|*.fcb';
if Opendialog1.execute then
begin
case Opendialog1.Filterindex of
1: LoadPlaylist(Opendialog1.filename, false, false);
2: LoadPlaylist(Opendialog1.filename, false, true);
end;
end;
{$ENDIF}
{$IFDEF MACOS}
LOpenDir := TNSOpenPanel.Wrap(TNSOpenPanel.OCClass.openPanel);
if AllocFilterStr('*.fcb|*.fcb', Filter) then
if LOpenDir.runModalForTypes(Filter)=1 then
LoadPlaylist(NSToDelphiString(LOpenDir.filename), false, false);
{$ENDIF}
end;

Make Disabled Menu and Toolbar Images look better?

Please see the attached screenshot which illustrates a TToolBar from one of my programs:
Notice the last two images of the Toolbar, they are disabled. The way they have been drawn to appear disabled is not very appealing, in fact in the Delphi IDE some of the images look the same.
The issue I have with it is I want my application to look a lot cleaner. The way the disabled items are drawn doesn't look very good. The TToolBar allows to set a disabled TImageList, I tried making my images black & white but they didn't look right, and would rather not have to always make the images black and white (time and effort). This problem also shows in my menus and popup menus, which don't allow for disabled images anyway.
Is there a way to paint the disabled items to look better on the eye?
If possible I would rather not look to use 3rd Party Controls. I know the Jedi Components allow disabled images for the menu etc, but would prefer a way to not resort too 3rd Party Components, when possible I would much prefer to use the standard issue VCL, especially as sometimes I use the TActionMainMenuBar to draw Office Style menus, which match the TToolBar when DrawingStyle is set to gradient.
EDIT
I have accepted RRUZ's answer, is it possible though to accept David's answer as well, both are very good answers and would like the answer to be shared between them if possible.
Thanks.
Sometime Ago i wrote a patch to fix this behavior. the key is patch the code of the TCustomImageList.DoDraw function, the technique used is similar to the used by the delphi-nice-toolbar app, but instead of patch a bpl IDE in this case we patch the function in memory.
Just include this unit in your project
unit uCustomImageDrawHook;
interface
uses
Windows,
SysUtils,
Graphics,
ImgList,
CommCtrl,
Math;
implementation
type
TJumpOfs = Integer;
PPointer = ^Pointer;
PXRedirCode = ^TXRedirCode;
TXRedirCode = packed record
Jump: Byte;
Offset: TJumpOfs;
end;
PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp;
TAbsoluteIndirectJmp = packed record
OpCode: Word;
Addr: PPointer;
end;
TCustomImageListHack = class(TCustomImageList);
var
DoDrawBackup : TXRedirCode;
function GetActualAddr(Proc: Pointer): Pointer;
begin
if Proc <> nil then
begin
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (PAbsoluteIndirectJmp(Proc).OpCode = $25FF) then
Result := PAbsoluteIndirectJmp(Proc).Addr^
else
Result := Proc;
end
else
Result := nil;
end;
procedure HookProc(Proc, Dest: Pointer; var BackupCode: TXRedirCode);
var
n: DWORD;
Code: TXRedirCode;
begin
Proc := GetActualAddr(Proc);
Assert(Proc <> nil);
if ReadProcessMemory(GetCurrentProcess, Proc, #BackupCode, SizeOf(BackupCode), n) then
begin
Code.Jump := $E9;
Code.Offset := PAnsiChar(Dest) - PAnsiChar(Proc) - SizeOf(Code);
WriteProcessMemory(GetCurrentProcess, Proc, #Code, SizeOf(Code), n);
end;
end;
procedure UnhookProc(Proc: Pointer; var BackupCode: TXRedirCode);
var
n: Cardinal;
begin
if (BackupCode.Jump <> 0) and (Proc <> nil) then
begin
Proc := GetActualAddr(Proc);
Assert(Proc <> nil);
WriteProcessMemory(GetCurrentProcess, Proc, #BackupCode, SizeOf(BackupCode), n);
BackupCode.Jump := 0;
end;
end;
procedure Bitmap2GrayScale(const BitMap: TBitmap);
type
TRGBArray = array[0..32767] of TRGBTriple;
PRGBArray = ^TRGBArray;
var
x, y, Gray: Integer;
Row : PRGBArray;
begin
BitMap.PixelFormat := pf24Bit;
for y := 0 to BitMap.Height - 1 do
begin
Row := BitMap.ScanLine[y];
for x := 0 to BitMap.Width - 1 do
begin
Gray := (Row[x].rgbtRed + Row[x].rgbtGreen + Row[x].rgbtBlue) div 3;
Row[x].rgbtRed := Gray;
Row[x].rgbtGreen := Gray;
Row[x].rgbtBlue := Gray;
end;
end;
end;
//from ImgList.GetRGBColor
function GetRGBColor(Value: TColor): DWORD;
begin
Result := ColorToRGB(Value);
case Result of
clNone:
Result := CLR_NONE;
clDefault:
Result := CLR_DEFAULT;
end;
end;
procedure New_Draw(Self: TObject; Index: Integer; Canvas: TCanvas; X, Y: Integer; Style: Cardinal; Enabled: Boolean);
var
MaskBitMap : TBitmap;
GrayBitMap : TBitmap;
begin
with TCustomImageListHack(Self) do
begin
if not HandleAllocated then Exit;
if Enabled then
ImageList_DrawEx(Handle, Index, Canvas.Handle, X, Y, 0, 0, GetRGBColor(BkColor), GetRGBColor(BlendColor), Style)
else
begin
GrayBitMap := TBitmap.Create;
MaskBitMap := TBitmap.Create;
try
GrayBitMap.SetSize(Width, Height);
MaskBitMap.SetSize(Width, Height);
GetImages(Index, GrayBitMap, MaskBitMap);
Bitmap2GrayScale(GrayBitMap);
BitBlt(Canvas.Handle, X, Y, Width, Height, MaskBitMap.Canvas.Handle, 0, 0, SRCERASE);
BitBlt(Canvas.Handle, X, Y, Width, Height, GrayBitMap.Canvas.Handle, 0, 0, SRCINVERT);
finally
GrayBitMap.Free;
MaskBitMap.Free;
end;
end;
end;
end;
procedure HookDraw;
begin
HookProc(#TCustomImageListHack.DoDraw, #New_Draw, DoDrawBackup);
end;
procedure UnHookDraw;
begin
UnhookProc(#TCustomImageListHack.DoDraw, DoDrawBackup);
end;
initialization
HookDraw;
finalization
UnHookDraw;
end.
and the result will be
I submitted a QC report for a related issue over a year ago, but that was for menus. I've never seen this for TToolbar since it is a wrapper to the common control and the drawing is handled by Windows.
However, the images you are seeing are clearly as result of the VCL calling TImageList.Draw and passing Enabled=False – nothing else looks that bad! Are you 100% sure this really is a TToolbar?
The fix will surely be to avoid TImageList.Draw and call ImageList_DrawIndirect with the ILS_SATURATE.
You may need to modify some VCL source. First find the location where the toolbar is being custom drawn and call this routine instead of the calls to TImageList.Draw.
procedure DrawDisabledImage(DC: HDC; ImageList: TCustomImageList; Index, X, Y: Integer);
var
Options: TImageListDrawParams;
begin
ZeroMemory(#Options, SizeOf(Options));
Options.cbSize := SizeOf(Options);
Options.himl := ImageList.Handle;
Options.i := Index;
Options.hdcDst := DC;
Options.x := X;
Options.y := Y;
Options.fState := ILS_SATURATE;
ImageList_DrawIndirect(#Options);
end;
An even better fix would be to work out why the toolbar is being custom drawn and find a way to let the system do it.
EDIT 1
I've looked at the Delphi source code and I'd guess that you are custom drawing the toolbar, perhaps because it has a gradient. I never even knew that TToolbar could handle custom drawing but I'm just a plain vanilla kind of guy!
Anyway, I can see code in TToolBar.GradientDrawButton calling the TImageList.Draw so I think the explanation above is on the right track.
I'm fairly sure that calling my DrawDisabledImage function above will give you better results. If could find a way to make that happen when you call TImageList.Draw then that would, I suppose, be the very best fix since it would apply wholesale.
EDIT 2
Combine the function above with #RRUZ's answer and you have an excellent solution.
Solution from #RRUZ dosn't work if you use LargeImages in ActionToolBar. I made changes to the #RRUZ code to work with LargeImages in ActionToolBar.
unit unCustomImageDrawHook;
interface
uses
Windows,
SysUtils,
Graphics,
ImgList,
CommCtrl,
Math,
Vcl.ActnMan,
System.Classes;
implementation
type
TJumpOfs = Integer;
PPointer = ^Pointer;
PXRedirCode = ^TXRedirCode;
TXRedirCode = packed record
Jump: Byte;
Offset: TJumpOfs;
end;
PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp;
TAbsoluteIndirectJmp = packed record
OpCode: Word;
Addr: PPointer;
end;
TCustomImageListHack = class(TCustomImageList);
TCustomActionControlHook = class(TCustomActionControl);
var
DoDrawBackup : TXRedirCode;
DoDrawBackup2 : TXRedirCode;
function GetActualAddr(Proc: Pointer): Pointer;
begin
if Proc <> nil then
begin
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (PAbsoluteIndirectJmp(Proc).OpCode = $25FF) then
Result := PAbsoluteIndirectJmp(Proc).Addr^
else
Result := Proc;
end
else
Result := nil;
end;
procedure HookProc(Proc, Dest: Pointer; var BackupCode: TXRedirCode);
var
n: SIZE_T;
Code: TXRedirCode;
begin
Proc := GetActualAddr(Proc);
Assert(Proc <> nil);
if ReadProcessMemory(GetCurrentProcess, Proc, #BackupCode, SizeOf(BackupCode), n) then
begin
Code.Jump := $E9;
Code.Offset := PAnsiChar(Dest) - PAnsiChar(Proc) - SizeOf(Code);
WriteProcessMemory(GetCurrentProcess, Proc, #Code, SizeOf(Code), n);
end;
end;
procedure UnhookProc(Proc: Pointer; var BackupCode: TXRedirCode);
var
n: SIZE_T;
begin
if (BackupCode.Jump <> 0) and (Proc <> nil) then
begin
Proc := GetActualAddr(Proc);
Assert(Proc <> nil);
WriteProcessMemory(GetCurrentProcess, Proc, #BackupCode, SizeOf(BackupCode), n);
BackupCode.Jump := 0;
end;
end;
procedure Bitmap2GrayScale(const BitMap: TBitmap);
type
TRGBArray = array[0..32767] of TRGBTriple;
PRGBArray = ^TRGBArray;
var
x, y, Gray: Integer;
Row : PRGBArray;
begin
BitMap.PixelFormat := pf24Bit;
for y := 0 to BitMap.Height - 1 do
begin
Row := BitMap.ScanLine[y];
for x := 0 to BitMap.Width - 1 do
begin
Gray := (Row[x].rgbtRed + Row[x].rgbtGreen + Row[x].rgbtBlue) div 3;
Row[x].rgbtRed := Gray;
Row[x].rgbtGreen := Gray;
Row[x].rgbtBlue := Gray;
end;
end;
end;
//from ImgList.GetRGBColor
function GetRGBColor(Value: TColor): DWORD;
begin
Result := ColorToRGB(Value);
case Result of
clNone:
Result := CLR_NONE;
clDefault:
Result := CLR_DEFAULT;
end;
end;
procedure New_Draw(Self: TObject; Index: Integer; Canvas: TCanvas; X, Y: Integer; Style: Cardinal; Enabled: Boolean);
var
MaskBitMap : TBitmap;
GrayBitMap : TBitmap;
begin
with TCustomImageListHack(Self) do
begin
if not HandleAllocated then Exit;
if Enabled then
ImageList_DrawEx(Handle, Index, Canvas.Handle, X, Y, 0, 0, GetRGBColor(BkColor), GetRGBColor(BlendColor), Style)
else
begin
GrayBitMap := TBitmap.Create;
MaskBitMap := TBitmap.Create;
try
GrayBitMap.SetSize(Width, Height);
MaskBitMap.SetSize(Width, Height);
GetImages(Index, GrayBitMap, MaskBitMap);
Bitmap2GrayScale(GrayBitMap);
BitBlt(Canvas.Handle, X, Y, Width, Height, MaskBitMap.Canvas.Handle, 0, 0, SRCERASE);
BitBlt(Canvas.Handle, X, Y, Width, Height, GrayBitMap.Canvas.Handle, 0, 0, SRCINVERT);
finally
GrayBitMap.Free;
MaskBitMap.Free;
end;
end;
end;
end;
procedure New_Draw2(Self: TObject; const Location: TPoint);
var
ImageList: TCustomImageList;
DrawEnabled: Boolean;
LDisabled: Boolean;
begin
with TCustomActionControlHook(Self) do
begin
if not HasGlyph then Exit;
ImageList := FindImageList(True, LDisabled, ActionClient.ImageIndex);
if not Assigned(ImageList) then Exit;
DrawEnabled := LDisabled or Enabled and (ActionClient.ImageIndex <> -1) or
(csDesigning in ComponentState);
ImageList.Draw(Canvas, Location.X, Location.Y, ActionClient.ImageIndex,
dsTransparent, itImage, DrawEnabled);
end;
end;
procedure HookDraw;
begin
HookProc(#TCustomImageListHack.DoDraw, #New_Draw, DoDrawBackup);
HookProc(#TCustomActionControlHook.DrawLargeGlyph, #New_Draw2, DoDrawBackup2);
end;
procedure UnHookDraw;
begin
UnhookProc(#TCustomImageListHack.DoDraw, DoDrawBackup);
UnhookProc(#TCustomActionControlHook.DrawLargeGlyph, DoDrawBackup2);
end;
initialization
HookDraw;
finalization
UnHookDraw;
end.
Take a look at this Delphi IDE fix. Maybe you can mimic it's implementation.
Use TActionToolbar , TActionmanager , Timagelist
Set action managers image list to a Timagelist. and set Disabledimages to another imagelist

How to get MAC address in windows7? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Getting Machine’s MAC Address — Good Solution?
How do I get the MAC address of a network card using Delphi?
I am using MAC address as hardware id for protection(ofcourse I have encrypted this data)
I am using below code to get MAC address on user computer
function MacAddress: string;
var
Lib: Cardinal;
Func: function(GUID: PGUID): Longint; stdcall;
GUID1, GUID2: TGUID;
begin
Result := '';
Lib := LoadLibrary('rpcrt4.dll');
if Lib <> 0 then
begin
#Func := GetProcAddress(Lib, 'UuidCreateSequential');
if Assigned(Func) then
begin
if (Func(#GUID1) = 0) and
(Func(#GUID2) = 0) and
(GUID1.D4[2] = GUID2.D4[2]) and
(GUID1.D4[3] = GUID2.D4[3]) and
(GUID1.D4[4] = GUID2.D4[4]) and
(GUID1.D4[5] = GUID2.D4[5]) and
(GUID1.D4[6] = GUID2.D4[6]) and
(GUID1.D4[7] = GUID2.D4[7]) then
begin
Result :=
IntToHex(GUID1.D4[2], 2) + '-' +
IntToHex(GUID1.D4[3], 2) + '-' +
IntToHex(GUID1.D4[4], 2) + '-' +
IntToHex(GUID1.D4[5], 2) + '-' +
IntToHex(GUID1.D4[6], 2) + '-' +
IntToHex(GUID1.D4[7], 2);
end;
end;
end;
end;
above code works perfectly on windows XP
but its giving different values in windows7 ,the value changing every time after computer resratred :(
is there any chance of getting MAC address thats constant (unless user changed his MAC address)
or is there any good code which retrvies constant data on all OS ?
thanks in advance
#steve0, to retrieve the mac address of an Network Adapter you can use the WMI and the Win32_NetworkAdapterConfiguration Class and check the MACAddress property.
Check this code:
program WMI_MAC;
{$APPTYPE CONSOLE}
uses
SysUtils
,ActiveX
,ComObj
,Variants;
function VarToStrNil(Value:Variant):string; //Dummy function to onvert an variant value to string
begin
if VarIsNull(Value) then
Result:=''
else
Result:=VarToStr(Value);
end;
Procedure GetMacAddress;
var
objWMIService : OLEVariant;
colItems : OLEVariant;
colItem : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
wmiHost, root, wmiClass: string;
function GetWMIObject(const objectName: String): IDispatch;
var
chEaten: Integer;
BindCtx: IBindCtx;//for access to a bind context
Moniker: IMoniker;//Enables you to use a moniker object
begin
OleCheck(CreateBindCtx(0, bindCtx));
OleCheck(MkParseDisplayName(BindCtx, StringToOleStr(objectName), chEaten, Moniker));//Converts a string into a moniker that identifies the object named by the string
OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result));//Binds to the specified object
end;
begin
wmiHost := '.';
root := 'root\CIMV2';
wmiClass := 'Win32_NetworkAdapterConfiguration';
objWMIService := GetWMIObject(Format('winmgmts:\\%s\%s',[wmiHost,root]));
colItems := objWMIService.ExecQuery(Format('SELECT * FROM %s',[wmiClass]),'WQL',0);
oEnum := IUnknown(colItems._NewEnum) as IEnumVariant;
while oEnum.Next(1, colItem, iValue) = 0 do
//if VarToStrNil(colItem.MACAddress)<>'' then //uncomment if you only want list the interfaces with mac adress
//if colItem.IPEnabled then // uncomment if you only want list the active interfaces
begin
WriteLn('Card Description '+VarToStrNil(colItem.Caption));
WriteLn('MACAddress '+VarToStrNil(colItem.MACAddress));
end;
end;
begin
try
CoInitialize(nil);
try
GetMacAddress;
Readln;
finally
CoUninitialize;
end;
except
on E:Exception do
Begin
Writeln(E.Classname, ': ', E.Message);
Readln;
End;
end;
end.
Here is some code working well for any computer on your network - may try it to get your own, using '127.0.0.1' as IP:
function GetRemoteMacAddress(const IP: AnsiString): TSockData;
// implements http://msdn.microsoft.com/en-us/library/aa366358(VS.85).aspx
type
TSendARP = function(DestIp: DWORD; srcIP: DWORD; pMacAddr: pointer; PhyAddrLen: Pointer): DWORD; stdcall;
const
HexChars: array[0..15] of AnsiChar = '0123456789ABCDEF';
var dwRemoteIP: DWORD;
PhyAddrLen: Longword;
pMacAddr : array [0..7] of byte;
I: integer;
P: PAnsiChar;
SendARPLibHandle: THandle;
SendARP: TSendARP;
begin
result := '';
SendARPLibHandle := LoadLibrary('iphlpapi.dll');
if SendARPLibHandle<>0 then
try
SendARP := GetProcAddress(SendARPLibHandle,'SendARP');
if #SendARP=nil then
exit; // we are not under 2K or later
dwremoteIP := inet_addr(pointer(IP));
if dwremoteIP<>0 then begin
PhyAddrLen := 8;
if SendARP(dwremoteIP, 0, #pMacAddr, #PhyAddrLen)=NO_ERROR then begin
if PhyAddrLen=6 then begin
SetLength(result,12);
P := pointer(result);
for i := 0 to 5 do begin
P[0] := HexChars[pMacAddr[i] shr 4];
P[1] := HexChars[pMacAddr[i] and $F];
inc(P,2);
end;
end;
end;
end;
finally
FreeLibrary(SendARPLibHandle);
end;
end;
This code is extracted from our freeware and open source framework, unit SynCrtSock.pas. See http://synopse.info/fossil

Resources