var
  vol:byte;
  mute,bMouseDown:boolean;

procedure OpenSetVolumeDialog;
begin
  ShellExecute(0,'open','sndvol32.exe','','',1);
end;

procedure RefreshVol;
var
  aVol:byte;
  aMute:boolean;
begin
  if not GetVolume(aVol,aMute) or ((aVol=vol) and (aMute=mute)) then exit;
  BeginUpdate;
  vol:=aVol;
  mute:=aMute;
  imgVol.Width:=round(imgVol.ActualWidth*vol/100);
  imgVolbg.NeedRefresh:=true;
  if not mute then
  begin
    imgIcon.hint:='静音';
    imgIcon.FileName:=WidgetPath+'images\kmix.png';
    lblVol.caption:='音量：'+inttostr(vol)+'%';
  end
  else
  begin
    imgIcon.hint:='取消静音';
    imgIcon.FileName:=WidgetPath+'images\kmix-mute.png';
    lblVol.caption:='静音';
  end;
  EndUpdate;
end;

//切换是否有声音
procedure SwitchMute;
begin
  SetVolume(vol,not mute);
  RefreshVol;
end;

//设置音量
procedure SetVol(value:integer);
var
  b:byte;
begin
  if value<0 then b:=0
  else if value>100 then b:=100
  else b:=value;
  if (b=vol) then exit;
  SetVolume(b,mute);
  RefreshVol;  
end;

//--- Widget鼠标滚轮事件，当在Widget上进行滚轮操作时会触发此事件 ---
procedure OnWidgetMouseWheel(WheelDelta);
begin
  if WheelDelta>0 then
    SetVol(vol+5)
  else
    SetVol(vol-5);
end;

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

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

//--- Widget初始化事件，当打开Widget时会触发此事件 ---
procedure OnWidgetInit;
begin
  vol:=-1;
  mute:=false;
  bMouseDown:=false;

  imgVolbg.OnMouseDown:='MouseDown';
  imgVol.OnMouseDown:='MouseDown';
  imgVolbg.OnMouseUp:='MouseUp';
  imgVol.OnMouseUp:='MouseUp';
  imgVolbg.OnMouseMove:='MouseMove';
  imgVol.OnMouseMove:='MouseMove';

  BeginUpdate;
  RefreshVol;  
  EndUpdate;
  tmr.Enabled:=true;
end;

//--- Widget关闭事件，当关闭Widget时会触发此事件 ---
procedure OnWidgetClose;
begin

end;

procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  bMouseDown:=true;
  SetVol(round(x*100/102));
  //showtrayhint('pos','x:'+inttostr(x)+' y:'+inttostr(y));
end;

procedure MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  if bMouseDown then
    SetVol(round(x*100/102));
end;

procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); 
begin
  bMouseDown:=false;
end;