디렉토리에 응용 프로그램 바로 가기 만들기
C #에서 또는 .NET Framework를 사용하여 응용 프로그램 바로 가기 (.lnk 파일)를 만드는 방법은 무엇입니까?
결과는 지정된 응용 프로그램 또는 URL에 대한 .lnk 파일입니다.
내가 좋아하는 것만 큼 간단하지는 않지만 vbAccelerator에 ShellLink.cs 라는 훌륭한 클래스 호출이 있습니다 .
이 코드는 interop을 사용하지만 WSH에 의존하지 않습니다.
이 클래스를 사용하여 바로 가기를 만드는 코드는 다음과 같습니다.
private static void configStep_addShortcutToStartupGroup()
{
using (ShellLink shortcut = new ShellLink())
{
shortcut.Target = Application.ExecutablePath;
shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
shortcut.Description = "My Shorcut Name Here";
shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
}
}
좋고 깨끗합니다. ( .NET 4.0 )
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
dynamic shell = Activator.CreateInstance(t);
try{
var lnk = shell.CreateShortcut("sc.lnk");
try{
lnk.TargetPath = @"C:\something";
lnk.IconLocation = "shell32.dll, 1";
lnk.Save();
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
추가 코드가 필요하지 않습니다. CreateShortcut 은 파일에서 바로 가기를로드 할 수도 있으므로 TargetPath 와 같은 속성이 기존 정보를 반환합니다. 바로 가기 개체 속성 .
동적 유형을 지원하지 않는 .NET 버전에서도이 방법이 가능합니다. ( .NET 3.5 )
Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object
object shell = Activator.CreateInstance(t);
try{
object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"});
try{
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{@"C:\whatever"});
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"});
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
}finally{
Marshal.FinalReleaseComObject(lnk);
}
}finally{
Marshal.FinalReleaseComObject(shell);
}
다음과 같은 것을 발견했습니다.
private void appShortcutToDesktop(string linkName)
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
{
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
sorrowman의 기사 "url-link-to-desktop"의 원본 코드
내가 찾은 모든 가능성을 조사한 후 ShellLink에 정착했습니다 .
//Create new shortcut
using (var shellShortcut = new ShellShortcut(newShortcutPath)
{
Path = path
WorkingDirectory = workingDir,
Arguments = args,
IconPath = iconPath,
IconIndex = iconIndex,
Description = description,
})
{
shellShortcut.Save();
}
//Read existing shortcut
using (var shellShortcut = new ShellShortcut(existingShortcut))
{
path = shellShortcut.Path;
args = shellShortcut.Arguments;
workingDir = shellShortcut.WorkingDirectory;
...
}
간단하고 효과적인 것 외에도 저자 (Mattias Sjögren, MS MVP)는 일종의 COM / PInvoke / Interop 전문가이며 그의 코드를 숙독하는 것은 대안보다 더 강력하다고 생각합니다.
바로 가기 파일은 여러 명령 줄 유틸리티 (C # /. NET에서 쉽게 호출 할 수 있음)로 만들 수도 있습니다. 나는 그들 중 어느 것도 시도한 적이 없지만 NirCmd (NirSoft에는 SysInternals와 같은 품질 도구가 있음)로 시작했습니다.
Unfortunately NirCmd can't parse shortcut files (only create them), but for that purpose TZWorks lp seems capable. It can even format its output as csv. lnk-parser looks good too (it can output both HTML and CSV).
Similar to IllidanS4's answer, using the Windows Script Host proved the be the easiest solution for me (tested on Windows 8 64 bit).
However, rather than importing the COM type manually through code, it is easier to just add the COM type library as a reference. Choose References->Add Reference...
, COM->Type Libraries
and find and add "Windows Script Host Object Model".
This imports the namespace IWshRuntimeLibrary
, from which you can access:
WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);
link.TargetPath=TargetPathName;
link.Save();
Credit goes to Jim Hollenhorst.
You also need to import of COM library IWshRuntimeLibrary
. Right click on your project -> add reference -> COM -> IWshRuntimeLibrary -> add and then use the following code snippet.
private void createShortcutOnDesktop(String executablePath)
{
// Create a new instance of WshShellClass
WshShell lib = new WshShellClass();
// Create the shortcut
IWshRuntimeLibrary.IWshShortcut MyShortcut;
// Choose the path for the shortcut
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+"\\AZ.lnk");
// Where the shortcut should point to
//MyShortcut.TargetPath = Application.ExecutablePath;
MyShortcut.TargetPath = @executablePath;
// Description for the shortcut
MyShortcut.Description = "Launch AZ Client";
StreamWriter writer = new StreamWriter(@"D:\AZ\logo.ico");
Properties.Resources.system.Save(writer.BaseStream);
writer.Flush();
writer.Close();
// Location for the shortcut's icon
MyShortcut.IconLocation = @"D:\AZ\logo.ico";
// Create the shortcut at the given path
MyShortcut.Save();
}
참고URL : https://stackoverflow.com/questions/234231/creating-application-shortcut-in-a-directory
'Program Tip' 카테고리의 다른 글
Jenkins 용 API 토큰을 얻는 방법 (0) | 2020.11.01 |
---|---|
복사본 대신 객체에 대한 const 참조 반환 (0) | 2020.11.01 |
Mercurial에서 git reset --hard HEAD를 어떻게합니까? (0) | 2020.11.01 |
'int main () {return (0);의 부동 소수점 예외 (SIGFPE) (0) | 2020.11.01 |
git이 내 파일이 변경되었음을 인식하지 못하여 git add가 작동하지 않는 이유 (0) | 2020.11.01 |