Tuesday, October 11, 2016

Create Shortcut with RunAs Administrator using VFP


Create Shortcut with RunAs Administrator using Visual FoxPro Code.

Function CreateShortcut
Lparameters lcExecutableFile,lcShortcutText,lcProgramDesc,llRunAsAdmin

lcTmpShortCutFile  = Addbs(Getenv("TEMP")) + Sys(2015)+".lnk"

oWsh = Createobject("wscript.shell")
cDeskpath = oWsh.SpecialFolders("desktop")

lcShortcutFile = cDeskpath+"\"+lcShortcutText+".lnk"
If llRunAsAdmin
oShort = oWsh.CreateShortcut(lcTmpShortCutFile)
Else
oShort = oWsh.CreateShortcut(lcShortcutFile)
Endif

oShort.TargetPath = lcExecutableFile
oShort.WorkingDirectory = Addbs(Justpath(lcExecutableFile))
oShort.Description = lcProgramDesc
oShort.Save

If llRunAsAdmin && Creating New Shortcut with RunAs option.

nhandle     = Fopen(lcTmpShortCutFile)
nFilesize     = Fseek(nhandle,0,2)
=Fclose(nhandle)
nhandle     = Fopen(lcTmpShortCutFile)

nHandle2     =  Fcreate(lcShortcutFile)
If nhandle     = -1  &&OR nHandle2 = -1
Wait Window [both source and destination files must be accessible]
=Fclose(nhandle)
=Fclose(nHandle2)
Return
Endif

nRemain     = nFilesize
i = 0
Do While !Feof(nhandle)
nChunk     = 1 && MIN(100,nRemain)
cTake     = Fread(nhandle,nChunk)

If i=21
cTake = Chr(32)  && a[0x15] |= 0x20; // flip the bit.  for RunAsAdmin
Endif

=Fwrite(nHandle2,cTake,nChunk)
nRemain = nRemain - nChunk

i = i + 1
If nRemain = 0
Exit
Endif
Enddo
=Fclose(nhandle)
=Fclose(nHandle2)

Delete File "&lcTmpShortCutFile"
Endif
Return

2 comments: