var
  aColor:integer;
  sColor:string;
  aHotkeyStart,aHotkeyCopy:string;

function GetSysColor(nIndex: Integer): DWORD; 
  stdcall; external 'user32.dll' name 'GetSysColor';

function ColorToRGB(Color: TColor): Longint;
begin
  if Color < 0 then
    Result := GetSysColor(Color and $000000FF)
  else
    Result := Color;
end;

function Byte(value:integer):integer;
begin
  result:=value mod 256;  //trunc(frac(value/100)*100);
end;

function GetRValue(rgb: DWORD): integer;
begin
  Result := Byte(rgb);
end;

function GetGValue(rgb: DWORD): integer;
begin
  Result := Byte(rgb shr 8);
end;

function GetBValue(rgb: DWORD): integer;
begin
  Result := Byte(rgb shr 16);
end;

procedure GetColor;
var
  s:string;
  i:integer;
begin
  try
    aColor:=GetScreenColorFromCurrentCursor;
    if shp.color<>aColor then
    begin
      BeginUpdate;
      shp.color:=aColor;
      shp.ColorTo:=aColor;
      i:=ColorToRGB(aColor);
      s:=ColorToHtmlStr(aColor);
      if lblInfo.caption<>s then
      lblInfo.caption:=s;
      lblColor.caption:=format('R:%d G:%d B:%d',[GetRValue(i),GetGValue(i),GetBValue(i)]);
      EndUpdate;
      sColor:=s;
    end;
  except
  
  end;
end;

procedure CopyColor;
begin
  ClipBoard.AsText:=sColor;
end;

//--- Widget初始化事件，当打开Widget时会触发此事件 ---
procedure OnWidgetInit;
begin
  aHotkeyStart:=GetSetting('Hotkey1','Ctrl+1');
  aHotkeyCopy:=GetSetting('Hotkey2','Ctrl+2');
  if not AddHotkey(aHotkeyStart) then
    showtrayhint('提示','注册开始/停止取色热键:'+aHotkeyStart+'失败！');
  if not AddHotkey(aHotkeyCopy) then 
    showtrayhint('提示','注册取色热键:'+aHotkeyCopy+'失败！');
    
  imgColor.Hint:='开始取色'#13#10'(热键:'+aHotkeyStart+')';
end;

//--- Widget关闭事件，当关闭Widget时会触发此事件 ---
procedure OnWidgetClose;
begin
  DelHotkey(aHotkeyStart);
  DelHotkey(aHotkeyCopy);
end;

//--- Widget移入边栏事件，当Widget被移到边栏上时会触发此事件 ---
procedure OnWidgetDock;
begin
  Widget.width:=136;
end;

//--- Widget移出边栏事件，当Widget被移出边栏时会触发此事件 ---
procedure OnWidgetUnDock;
begin
  Widget.width:=142;
end;

procedure PickColor;
begin
  tmr.Enabled:=not tmr.Enabled;
  BeginUpdate;
  if tmr.Enabled then
  begin
    imgColor.FileName:=WidgetPath+'btn_ColorGray.png';
    imgColor.Hint:='停止取色';
    lblHint.caption:='取色中...';
  end
  else
  begin
    imgColor.FileName:=WidgetPath+'btn_Color.png';
    imgColor.Hint:='开始取色';
    lblHint.caption:='停止取色';
  end;
  imgColor.Hint:=imgColor.Hint+#13#10'(热键:'+aHotkeyStart+')';
  EndUpdate;
end;

//--- 当脚本定义的热键按下时触发此事件 ---
procedure OnHotKeyPressed(sHotkey:string);
begin
  if sHotkey=aHotkeyStart then PickColor
    else if sHotkey=aHotkeyCopy then CopyColor;
end;

