Can Inno Setup send key and mouse presses, if not, how can this be done using an Installer? - automation

I'm a newbie to both [Microsoft Windows] installers and Inno Setup but I need to know if Inno Setup (or an equivalent) can be used automate the input to a GUI-based windows program, during install, e.g. by clicking on a menu and selecting a sub-item, for instance?
I'm aware of AutoIt and AutoHotkey, as well as NSIS, however Inno Setup comes highly recommended as a software packager/installer, and I also like the idea of learning a little Pascal programming, into the bargain ;)
Any ideas or thoughts are most welcome :-)

I agree with #Deanna, the SendInput function is the best for simulating user input you can get. In the following script I've shown how to simulate mouse clicks on the absolute screen position (in pixels). As an example I'm trying to show Inno Setup's about box through the Help / About Inno Setup menu item (if you would have the same screen settings as me and have the Inno Setup IDE maximized, it may even hit that menu item. So here's just the mouse part (and only limited functionality you can get). Take it rather as a proof, that it's possible to simulate user input from Inno Setup:
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
OutputDir=userdocs:Inno Setup Examples Output
[code]
const
SM_CXSCREEN = 0;
SM_CYSCREEN = 1;
INPUT_MOUSE = 0;
MOUSEEVENTF_MOVE = $0001;
MOUSEEVENTF_LEFTDOWN = $0002;
MOUSEEVENTF_LEFTUP = $0004;
MOUSEEVENTF_RIGHTDOWN = $0008;
MOUSEEVENTF_RIGHTUP = $0010;
MOUSEEVENTF_MIDDLEDOWN = $0020;
MOUSEEVENTF_MIDDLEUP = $0040;
MOUSEEVENTF_VIRTUALDESK = $4000;
MOUSEEVENTF_ABSOLUTE = $8000;
type
TMouseInput = record
Itype: DWORD;
dx: Longint;
dy: Longint;
mouseData: DWORD;
dwFlags: DWORD;
time: DWORD;
dwExtraInfo: DWORD;
end;
function GetSystemMetrics(nIndex: Integer): Integer;
external 'GetSystemMetrics#user32.dll stdcall';
function SendMouseInput(nInputs: UINT; pInputs: TMouseInput;
cbSize: Integer): UINT;
external 'SendInput#user32.dll stdcall';
function SendMouseClick(Button: TMouseButton; X, Y: Integer): Boolean;
var
Flags: DWORD;
Input: TMouseInput;
ScreenWidth: Integer;
ScreenHeight: Integer;
begin
Result := False;
Flags := MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_VIRTUALDESK or MOUSEEVENTF_MOVE;
ScreenWidth := GetSystemMetrics(SM_CXSCREEN);
ScreenHeight := GetSystemMetrics(SM_CYSCREEN);
Input.Itype := INPUT_MOUSE;
Input.dx := Round((X * 65536) / ScreenWidth);
Input.dy := Round((Y * 65536) / ScreenHeight);
case Button of
mbLeft: Input.dwFlags := Flags or MOUSEEVENTF_LEFTDOWN;
mbRight: Input.dwFlags := Flags or MOUSEEVENTF_RIGHTDOWN;
mbMiddle: Input.dwFlags := Flags or MOUSEEVENTF_MIDDLEDOWN;
end;
Result := SendMouseInput(1, Input, SizeOf(Input)) = 1;
if Result then
begin
Input.Itype := INPUT_MOUSE;
Input.dx := Round((X * 65536) / ScreenWidth);
Input.dy := Round((Y * 65536) / ScreenHeight);
case Button of
mbLeft: Input.dwFlags := Flags or MOUSEEVENTF_LEFTUP;
mbRight: Input.dwFlags := Flags or MOUSEEVENTF_RIGHTUP;
mbMiddle: Input.dwFlags := Flags or MOUSEEVENTF_MIDDLEUP;
end;
Result := SendMouseInput(1, Input, SizeOf(Input)) = 1;
end;
end;
procedure InitializeWizard;
begin
if MsgBox('Are you sure you want to let the installer click ' +
'somewhere on your screen ? TLama warned you :-)', mbConfirmation,
MB_YESNO) = IDYES then
begin
if not SendMouseClick(mbLeft, 242, 31) then
MsgBox(SysErrorMessage(DLLGetLastError), mbError, mb_Ok);
if not SendMouseClick(mbLeft, 382, 263) then
MsgBox(SysErrorMessage(DLLGetLastError), mbError, mb_Ok);
end;
end;

The best bet for this is to use the SendInput() API from a DLL that you then call from Inno Setup.
This will allow full control of everything you can do manually in that application.

Related

Input and output pipe in Lazarus TProcess

I would like to make a terminal with a Lazarus GUI application. But I'm in trouble. And I hope someone can help me, please.
Question1: The Chinese and other special chars cannot display normally, I would like to know how to fix this problem.
(code)Class of the thread and "run" button on click event
screenshot
Question2: I want to know how to input some command into the console. I tried to start a Windows cmd, and use "winver" command. But when I click the button, nothing happened.
The send command button
Winver is not console but a GUI program. To run a program with output into memo, use the following code, which retrieves version using the cmd.exe "ver" command. You can try to use this template for the first question too.
unit mainprocesstomemo;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Process, Pipes;
Type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
public
procedure ProcessEvent(Sender,Context : TObject;Status:TRunCommandEventCode;const Message:string);
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TProcessMemo }
Type
TProcessToMemo = class(TProcess)
public
fmemo : Tmemo;
bytesprocessed : integer;
fstringsadded : integer;
function ReadInputStream(p:TInputPipeStream;var BytesRead:integer;var DataLength:integer;var Data:string;MaxLoops:integer=10):boolean;override;
end;
function RunCommandMemo(const exename:TProcessString;const commands:array of TProcessString;out outputstring:string; Options : TProcessOptions = [];SWOptions:TShowWindowOptions=swoNone;memo:TMemo=nil;runrefresh : TOnRunCommandEvent=nil ):boolean;
Var
p : TProcessToMemo;
i,
exitstatus : integer;
ErrorString : String;
begin
p:=TProcessToMemo.create(nil);
if Options<>[] then
P.Options:=Options - [poRunSuspended,poWaitOnExit];
p.options:=p.options+[poRunIdle];
P.ShowWindow:=SwOptions;
p.Executable:=exename;
if high(commands)>=0 then
for i:=low(commands) to high(commands) do
p.Parameters.add(commands[i]);
p.fmemo:=memo;
p.OnRunCommandEvent:=runrefresh;
try
result:=p.RunCommandLoop(outputstring,errorstring,exitstatus)=0;
finally
p.free;
end;
if exitstatus<>0 then result:=false;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var s : string;
begin
//RunCommandMemo('testit',[],s,[],swonone,memo1,ProcessEvent);
RunCommandMemo('cmd.exe',['/w','/c','ver'],s,[],swonone,memo1,ProcessEvent);
end;
procedure TForm1.ProcessEvent(Sender, Context: TObject;
Status: TRunCommandEventCode; const Message: string);
begin
if status in [RunCommandIdle, RunCommandFinished] then
begin
if status =RunCommandFinished then
begin
memo1.lines.add(' process finished');
end;
if tprocesstomemo(sender).fstringsadded>0 then
begin
tprocesstomemo(sender).fstringsadded:=0;
// memo1.lines.add('Handle:'+inttostr(tprocesstomemo(sender).ProcessHandle));
memo1.refresh;
end;
sleep(10);
application.ProcessMessages;
end;
end;
{ TProcessToMemo }
function TProcessToMemo.ReadInputStream(p:TInputPipeStream;var BytesRead:integer;var DataLength:integer;var Data:string;MaxLoops:integer=10):boolean;
var lfpos : integer;
crcorrectedpos:integer;
stradded : integer;
newstr : string;
begin
Result:=inherited ReadInputStream(p, BytesRead, DataLength, data, MaxLoops);
if (result) and (bytesread>bytesprocessed)then
begin
stradded:=0;
lfpos:=pos(#10,data,bytesprocessed+1);
while (lfpos<>0) and (lfpos<=bytesread) do
begin
crcorrectedpos:=lfpos;
if (crcorrectedpos>0) and (data[crcorrectedpos-1]=#13) then
dec(crcorrectedpos);
newstr:=copy(data,bytesprocessed+1,crcorrectedpos-bytesprocessed-1);
fmemo.lines.add(newstr);
inc(stradded);
bytesprocessed:=lfpos;
lfpos:=pos(#10,data,bytesprocessed+1);
end;
inc(fstringsadded,stradded); // check idle event.
end;
end;
end.
I don't know minecraft server, and many external programs might do weird things to the console. But a simple combination of programs to test with is here http://www.stack.nl/~marcov/files/processmemodemo.zip

Run Windows Explorer beside my application with a specified Bounds

I have this:
ShellExecute(Application.Handle, nil, PWideChar('explorer.exe'), PWideChar(ImagesDir), nil, SW_SHOWNORMAL);
where the variable ImagesDir is the directory of Images that I want to show by the Windows Explorer...
How can I run the Windows Explorer beside my application at a specified Bounds, for exemple like this?
when you open any File Explorer window (such as going to C:\ ), File Explorer has a specific saved window size that it opens with. So when you resize it, either horizontally and/or vertically, close it and re-open it again, it saves the size of the window, and the location within the Registry where this information is saved is this:
On my system, HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell\WinPos1366x768x96(1)..position, where position is left, right, top or bottom, gives the position of the window border in pixels.
I assume the name of the key depends on the screen resolution.here
and the code will be like that:
.....
const
AMainKey = '\Software\Classes\Local
Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell\';
var
FrmMain: TFrmMain;
ImagesDir: string;
AWinPos_left, AWinPos_Top,
AWinPos_Right, AWinPos_Bottom: string;
implementation
Uses
ShellApi, Registry;
{$R *.dfm}
procedure ExploreDir_With_Bounds(AFile_Dir: string;ALeft, ATop, AWidth, AHieght: DWORD);
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
BEGIN
Result :=(ShellExecute(GetDesktopWindow,'open',PWideChar(Dir),'','',SW_SHOW)>32)
END;
var
ListNames, ListPosition: TStringList;
I, AScreen_Width, AScreen_Hieght, APixelPI: Integer;
AWinPos_Uses: string;
begin
ListNames := TStringList.Create;
ListPosition := TStringList.Create;
With TRegistry.Create Do
Try
RootKey := HKEY_CURRENT_USER;
OpenKey(AMainKey,FALSE);
GetValueNames(ListNames);
AScreen_Width := Screen.Width;
AScreen_Hieght := Screen.Height;
APixelPI := Screen.PixelsPerInch;
AWinPos_Uses := 'WinPos'+AScreen_Width.ToString+'x'+AScreen_Hieght.ToString+'x'+APixelPI.ToString;
for I := 0 to ListNames.Count - 1 do
begin
if Pos(AWinPos_Uses, ListNames[I]) <> 0 then
begin
ListPosition.Add(ListNames[I]);
end;
end;
for I := 0 to ListPosition.Count - 1 do
begin
if (Pos('left', ListPosition[I]) <> 0) then
begin
AWinPos_left := ListPosition[I];
Lbl_Left.Caption := AWinPos_left;
Continue;
end else
if (Pos('top', ListPosition[I]) <> 0) then
begin
AWinPos_Top := ListPosition[I];
Lbl_Top.Caption := AWinPos_Top;
Continue;
end else
if (Pos('right', ListPosition[I]) <> 0) then
begin
AWinPos_Right := ListPosition[I];
Lbl_Right.Caption := AWinPos_Right;
Continue;
end else
if (Pos('bottom', ListPosition[I]) <> 0) then
begin
AWinPos_Bottom := ListPosition[I];
Lbl_Bottom.Caption := AWinPos_Bottom;
end;
end;
if (AWinPos_left <> '')and(AWinPos_Top <> '')and
(AWinPos_Right <> '')and(AWinPos_Bottom <> '') then
begin
WriteInteger(AWinPos_left, ALeft);
WriteInteger(AWinPos_Top, ATop);
WriteInteger(AWinPos_Right, ALeft + AWidth);
WriteInteger(AWinPos_Bottom, ATop + AHieght);
end;
CloseKey;
Finally
Free;
ListNames.Free;
ListPosition.Free;
End;
ExploreDirectory(AFile_Dir);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
ImagesDir := TDirectory.GetParent(TDirectory.GetParent(ExtractFileDir(ParamStr(0))))+ '\My Images To Test';
ExploreDir_With_Bounds(ImagesDir, (50 + Width)+10{Left}, 50{TOP},
Screen.Width - (Left + Width +20){width},
Screen.Height - 150{hieght});
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
Left := 0;
Top := (Screen.WorkAreaHeight div 2)-(Height div 2);
end;
end.
the Result here
You can use the following function to open an explorer window and have it point to a specific directory.
USES Windows,ShellAPI;
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
BEGIN
Result:=(ShellExecute(GetDesktopWindow,'open',PChar(Dir),'','',SW_SHOW)>32)
END;
Note, however, that you can't (with this code) make the Explorer window "follow" your program, ie. the opened window is a completely autonomous window that has no link to your program, just as if the user had browsed to the directory himself. If you call this function again with a new directory, Explorer will open a new window with that directory (and keep the old one opened).
UPDATE:
If you want to be able to manipulate the explorer window after it is opened, you need to use the various interfaces that Explorer exposes. I have made a UNIT that allows you to do what you seek as well as returning the interface needed to be able to manipulate the window afterwards. It is heavily based on the code found in this answer:
Check if windows explorer already opened on given path
by Victoria
UNIT WindowsExplorer;
INTERFACE
USES Types,ShDocVw;
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
FUNCTION OpenFolder(CONST Dir : STRING) : IWebBrowserApp; OVERLOAD;
FUNCTION OpenFolderAt(CONST Dir : STRING ; Left,Top,Width,Height : INTEGER) : IWebBrowserApp; OVERLOAD;
FUNCTION OpenFolderAt(CONST Dir : STRING ; CONST Rect : TRect) : IWebBrowserApp; OVERLOAD; INLINE;
IMPLEMENTATION
USES Windows,Variants,ShlObj,Ole2,OleAuto,ShellAPI,ActiveX,SysUtils;
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
BEGIN
Result:=(ShellExecute(GetDesktopWindow,'open',PChar(Dir),'','',SW_SHOW)>32)
END;
FUNCTION GetFolderIDList(CONST Dir : STRING) : PItemIDList;
VAR
ShellFolder : IShellFolder;
Attributes : ULONG;
Count : ULONG;
BEGIN
OleCheck(SHGetDesktopFolder(ShellFolder));
Attributes:=SFGAO_FOLDER or SFGAO_STREAM;
OleCheck(ShellFolder.ParseDisplayName(0,NIL,PWideChar(WideString(Dir)),Count,Result,Attributes));
IF NOT ((Attributes AND SFGAO_FOLDER=SFGAO_FOLDER) AND (Attributes AND SFGAO_STREAM<>SFGAO_STREAM)) THEN BEGIN
CoTaskMemFree(Result);
Result:=NIL
END
END;
FUNCTION OpenFolder(CONST Dir : STRING ; OpenIfNotFound : BOOLEAN) : IWebBrowserApp; OVERLOAD;
CONST
IID_IServiceProvider: System.TGUID = '{6D5140C1-7436-11CE-8034-00AA006009FA}';
VAR
FolderID : PItemIDList;
ShellWindows : IShellWindows;
I : INTEGER;
WndIFace : System.IDispatch;
WebBrowserApp : IWebBrowserApp;
ServiceProvider : IServiceProvider;
ShellBrowser : IShellBrowser;
ShellView : IShellView;
FolderView : IFolderView;
PersistFolder : IPersistFolder2;
CurFolderID : PItemIDList;
BEGIN
FolderID:=GetFolderIDList(Dir);
IF Assigned(FolderID) THEN TRY
OleCheck(CoCreateInstance(CLASS_ShellWindows,NIL,CLSCTX_LOCAL_SERVER,IID_IShellWindows,ShellWindows));
FOR I:=0 TO PRED(ShellWindows.Count) DO BEGIN
WndIface:=ShellWindows.Item(VarAsType(I,VT_I4));
IF Assigned(WndIface) AND
Succeeded(WndIface.QueryInterface(IID_IWebBrowserApp,WebBrowserApp)) AND
Succeeded(WebBrowserApp.QueryInterface(IID_IServiceProvider,ServiceProvider)) AND
Succeeded(ServiceProvider.QueryService(SID_STopLevelBrowser,IID_IShellBrowser,ShellBrowser)) AND
Succeeded(ShellBrowser.QueryActiveShellView(ShellView)) AND
Succeeded(ShellView.QueryInterface(IID_IFolderView,FolderView)) AND
Succeeded(FolderView.GetFolder(IID_IPersistFolder2,PersistFolder)) AND
Succeeded(PersistFolder.GetCurFolder(CurFolderID)) AND
ILIsEqual(FolderID,CurFolderID) THEN BEGIN
IF IsIconic(WebBrowserApp.HWnd) THEN Win32Check(ShowWindow(WebBrowserApp.HWnd,SW_RESTORE));
Win32Check(SetForegroundWindow(WebBrowserApp.HWnd));
Exit(WebBrowserApp)
END
END
FINALLY
CoTaskMemFree(FolderID)
END;
Result:=NIL;
IF OpenIfNotFound THEN BEGIN
IF NOT ExploreDirectory(Dir) THEN EXIT;
FOR I:=1 TO 20 DO BEGIN
Result:=OpenFolder(Dir,FALSE);
IF Assigned(Result) THEN EXIT;
Sleep(100)
END
END
END;
FUNCTION OpenFolder(CONST Dir : STRING) : IWebBrowserApp;
BEGIN
Result:=OpenFolder(Dir,TRUE)
END;
FUNCTION OpenFolderAt(CONST Dir : STRING ; Left,Top,Width,Height : INTEGER) : IWebBrowserApp;
BEGIN
Result:=OpenFolder(Dir);
IF Assigned(Result) THEN BEGIN
Result.Left:=Left; Result.Top:=Top; Result.Width:=Width; Result.Height:=Height
END
END;
FUNCTION OpenFolderAt(CONST Dir : STRING ; CONST Rect : TRect) : IWebBrowserApp;
BEGIN
Result:=OpenFolderAt(Dir,Rect.Left,Rect.Top,Rect.Width,Rect.Height)
END;
END.
It is made for use with Delphi Tokyo 10.2.3 so if you use an earlier version (you didn't specify Delphi version in your question), you may need to adapt the USES list to match.

How to get the height and width of the visible browser area

How can I retrieve the height and width of the browser area?
I want to show one form always in landscape mode, regardless whether the mobile phone has rotated the browser view.
if the browser is in portrait postion I want to rotate the form (TForm.Angel := 90). In order to force landscape mode.
Update:
Here is a picture, how the result should look like:
I found a solution, but I am not so really happy with it. It's easy to rotate the view, but the origin is not in the center, so I have to manually correct it, and I don't understand why this transformation is neccessary.
Here is the code:
procedure TForm1.ForceLandscape(aEnabled: Boolean);
var
browserWidth, browserHeight: Integer;
isLandscapeMode: Boolean;
begin
browserHeight := Application.Display.ClientHeight; //BrowserAPI.Window.innerHeight;
browserWidth := Application.Display.ClientWidth; //BrowserAPI.Window.innerWidth;
isLandscapeMode := browserHeight > browserWidth;
if aEnabled and isLandscapeMode then
begin
Angle := 90;
Height := browserWidth;
Width := browserHeight;
end
else
begin
Angle := 0;
Height := browserHeight;
Width := browserWidth;
end;
end;
procedure TForm1.InitializeForm;
begin
inherited;
// this is a good place to initialize components
//Need to put a transform.orign for form rotation (Angle)
var x := trunc(Application.Display.ClientWidth / 2);
var myStyle := TInteger.ToPxStr(x) + ' ' + TInteger.ToPxStr(x);
w3_setStyle(Handle, w3_CSSPrefix('TransformOrigin'), myStyle);
end;
The simplest way would be to use the main form's With and Height.
Create a new "Visual project" and add an EditBox to the form.
Put this code into the "Resize" method:
Edit1.Text := Format('%d x %d', [Self.Width, Self.Height]);
If you, however, want to keep the main-form at a fixed size, you would need to read some other properties.
Self.Width := 250;
Self.Height := 250;
There are several ways to get these dimensions. Both the "window" and "document" DOM-element have some properties you can use:
window.innerWidth
document.documentElement.clientWidth
document.body.clientWidth
In Smart you can access these from the Application object:
(Add two more edit-boxes...)
W3EditBox2.Text := Format('%d x %d', [Application.Document.ClientWidth, Application.Document.ClientHeight]);
W3EditBox3.Text := Format('%d x %d', [Application.Display.ClientWidth, Application.Display.ClientHeight]);
It seems to be a bug in Application.Document.ClientHeight as it always returns 0...
Remember that the running code is JavaScript. You can find lots of useful information on the web.
It's very easy to transform these JS-snippets into Smart Pascal via an asm section.
Eg:
var
w,h: Integer;
begin
//Pure JavaScript below.
//The #-prefix maps the variable to a SmartPascal declared variable
asm
#w = window.innerWidth;
#h = window.innerHeight;
end;
W3EditBox4.Text := Format('%d x %d', [w, h]);
end;
Another trick would be to declare a Variant variable.
A Variant variable can hold a whole JavaScript object, and enable "late binding"-ish access to the members of the object:
var
v: Variant;
begin
//Grab the whole "document" element from the DOM
asm
#v = document;
end;
//Access all "document" members directly via the "v"-variable
W3EditBox5.Text := Format('%d x %d', [v.documentElement.clientWidth, v.documentElement.clientHeight]);
end;
Screenshot of the code-snippets above:

.NET Framework as a pre-requisite for installation with Inno-Setup

I have an application I have to check if .NET FW 3.5 has already installed. If already installed, I want to open a messagebox that asks the user to download it from Microsoft website and stop the installation.
I found the following code. Can you tell me please:
a) Where should I call this function from?
b) Should I check if .NET FW 3.5 or higher version is already installed? e.g. If FW 4.0 installed - is that necessary to install 3.5?
Thank you
function IsDotNET35Detected(): Boolean;
var
ErrorCode: Integer;
netFrameWorkInstalled : Boolean;
isInstalled: Cardinal;
begin
result := true;
// Check for the .Net 3.5 framework
isInstalled := 0;
netFrameworkInstalled := RegQueryDWordValue(HKLM, 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5', 'Install', isInstalled);
if ((netFrameworkInstalled) and (isInstalled <> 1)) then netFrameworkInstalled := false;
if netFrameworkInstalled = false then
begin
if (MsgBox(ExpandConstant('{cm:dotnetmissing}'), mbConfirmation, MB_YESNO) = idYes) then
begin
ShellExec('open',
'http://www.microsoft.com/downloads/details.aspx?FamilyID=333325fd-ae52-4e35-b531-508d977d32a6&DisplayLang=en',
'','',SW_SHOWNORMAL,ewNoWait,ErrorCode);
end;
result := false;
end;
end;
If you want to perform your check when the installation starts but before the wizard form is shown, use the InitializeSetup event handler for it. When you return False to that handler, the setup will abort, when True, setup will start. Here's a little bit optimized script you've posted:
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
[CustomMessages]
DotNetMissing=.NET Framework 3.5 is missing. Do you want to download it ? Setup will now exit!
[Code]
function IsDotNET35Detected: Boolean;
var
ErrorCode: Integer;
InstallValue: Cardinal;
begin
Result := True;
if not RegQueryDWordValue(HKLM, 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5',
'Install', InstallValue) or (InstallValue <> 1) then
begin
Result := False;
if MsgBox(ExpandConstant('{cm:DotNetMissing}'), mbConfirmation, MB_YESNO) = IDYES then
ShellExec('', 'http://www.microsoft.com/downloads/details.aspx?FamilyID=333325fd-ae52-4e35-b531-508d977d32a6&DisplayLang=en',
'', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;
end;
function InitializeSetup: Boolean;
begin
Result := IsDotNET35Detected;
end;

Is it possible to 'Pin to start menu' using Inno Setup?

I'm using the excellent Inno Setup installer and I notice that some Applications (often from Microsoft) get installed with their launch icon already highly visible ('pinned?') in the start menu (in Windows 7). Am I totally reliant on the most-recently-used algorithm for my icon to be 'large' in the start menu, or is there a way of promoting my application from the installer please?
It is possible to pin programs, but not officially. Based on a code posted in this thread (which uses the same way as described in the article linked by #Mark Redman) I wrote the following:
[Code]
#ifdef UNICODE
#define AW "W"
#else
#define AW "A"
#endif
const
// these constants are not defined in Windows
SHELL32_STRING_ID_PIN_TO_TASKBAR = 5386;
SHELL32_STRING_ID_PIN_TO_STARTMENU = 5381;
SHELL32_STRING_ID_UNPIN_FROM_TASKBAR = 5387;
SHELL32_STRING_ID_UNPIN_FROM_STARTMENU = 5382;
type
HINSTANCE = THandle;
HMODULE = HINSTANCE;
TPinDest = (
pdTaskbar,
pdStartMenu
);
function LoadLibrary(lpFileName: string): HMODULE;
external 'LoadLibrary{#AW}#kernel32.dll stdcall';
function FreeLibrary(hModule: HMODULE): BOOL;
external 'FreeLibrary#kernel32.dll stdcall';
function LoadString(hInstance: HINSTANCE; uID: UINT;
lpBuffer: string; nBufferMax: Integer): Integer;
external 'LoadString{#AW}#user32.dll stdcall';
function TryGetVerbName(ID: UINT; out VerbName: string): Boolean;
var
Buffer: string;
BufLen: Integer;
Handle: HMODULE;
begin
Result := False;
Handle := LoadLibrary(ExpandConstant('{sys}\Shell32.dll'));
if Handle <> 0 then
try
SetLength(Buffer, 255);
BufLen := LoadString(Handle, ID, Buffer, Length(Buffer));
if BufLen <> 0 then
begin
Result := True;
VerbName := Copy(Buffer, 1, BufLen);
end;
finally
FreeLibrary(Handle);
end;
end;
function ExecVerb(const FileName, VerbName: string): Boolean;
var
I: Integer;
Shell: Variant;
Folder: Variant;
FolderItem: Variant;
begin
Result := False;
Shell := CreateOleObject('Shell.Application');
Folder := Shell.NameSpace(ExtractFilePath(FileName));
FolderItem := Folder.ParseName(ExtractFileName(FileName));
for I := 1 to FolderItem.Verbs.Count do
begin
if FolderItem.Verbs.Item(I).Name = VerbName then
begin
FolderItem.Verbs.Item(I).DoIt;
Result := True;
Exit;
end;
end;
end;
function PinAppTo(const FileName: string; PinDest: TPinDest): Boolean;
var
ResStrID: UINT;
VerbName: string;
begin
case PinDest of
pdTaskbar: ResStrID := SHELL32_STRING_ID_PIN_TO_TASKBAR;
pdStartMenu: ResStrID := SHELL32_STRING_ID_PIN_TO_STARTMENU;
end;
Result := TryGetVerbName(ResStrID, VerbName) and ExecVerb(FileName, VerbName);
end;
function UnpinAppFrom(const FileName: string; PinDest: TPinDest): Boolean;
var
ResStrID: UINT;
VerbName: string;
begin
case PinDest of
pdTaskbar: ResStrID := SHELL32_STRING_ID_UNPIN_FROM_TASKBAR;
pdStartMenu: ResStrID := SHELL32_STRING_ID_UNPIN_FROM_STARTMENU;
end;
Result := TryGetVerbName(ResStrID, VerbName) and ExecVerb(FileName, VerbName);
end;
The above code first reads the caption of the menu item for pinning or unpinning applications from the string table of the Shell32.dll library. Then connects to the Windows Shell, and for the target app. path creates the Folder object, then obtains the FolderItem object and on this object iterates all the available verbs and checks if their name matches to the one read from the Shell32.dll library string table. If so, it invokes the verb item action by calling the DoIt method and exits the iteration.
Here is a possible usage of the above code, for pinning:
if PinAppTo(ExpandConstant('{sys}\calc.exe'), pdTaskbar) then
MsgBox('Calc has been pinned to the taskbar.', mbInformation, MB_OK);
if PinAppTo(ExpandConstant('{sys}\calc.exe'), pdStartMenu) then
MsgBox('Calc has been pinned to the start menu.', mbInformation, MB_OK);
And for unpinning:
if UnpinAppFrom(ExpandConstant('{sys}\calc.exe'), pdTaskbar) then
MsgBox('Calc is not pinned to the taskbar anymore.', mbInformation, MB_OK);
if UnpinAppFrom(ExpandConstant('{sys}\calc.exe'), pdStartMenu) then
MsgBox('Calc is not pinned to the start menu anymore.', mbInformation, MB_OK);
Please note that even though this code works on Windows 7 (and taskbar pinning also on Windows 8.1 where I've tested it), it is really hacky way, since there is no official way to programatically pin programs to taskbar, nor start menu. That's what the users should do by their own choice.
There's a reason there's no programmatic way to pin things to the taskbar/start menu. In my experience, I have seen the start menu highlight newly-created shortcuts, and that's designed to handle exactly this situation. When you see a newly-installed program show up on the start menu, it's probably because of that algorithm and not because the installer placed it there.
That said, if a new shortcut does not appear highlighted, it may be because the installer extracts a pre-existing shortcut and preserves an old timestamp on it, rather than using the API function to create a shortcut in the start menu.
Have a look at: http://blogs.technet.com/deploymentguys/archive/2009/04/08/pin-items-to-the-start-menu-or-windows-7-taskbar-via-script.aspx