C# 加载本地文件设置应用程序图标
- static class Program
- {
- [STAThread]
- static void Main()
- {
- Application.EnableVisualStyles();
- Application.SetCompatibleTextRenderingDefault(false);
-
- Form mainForm = new Form1();
- mainForm.Show();
-
- //IntPtr hProcess = Process.GetCurrentProcess().MainWindowHandle;
-
- // 设置应用程序图标
- SetApplicationIcon(@"./vip.ico");
-
- string exeFilePath = Assembly.GetEntryAssembly().Location;
- CreateShortcut(exeFilePath, @"C:\Users\Admin\Desktop\shortcut.lnk");
- Application.Run(mainForm);
- }
-
- static void SetApplicationIcon(string iconFilePath)
- {
- // 从资源文件中加载图标
- Icon icon = Icon.ExtractAssociatedIcon(iconFilePath);
-
- // 将图标设置为应用程序的主图标
- IntPtr hIcon = icon.Handle;
- SendMessage(hProcess, WM_SETICON, ICON_SMALL, hIcon);
- SendMessage(hProcess, WM_SETICON, ICON_BIG, hIcon);
-
- // 释放资源
- //icon.Dispose();
- }
-
- const int WM_SETICON = 0x80;
- const int ICON_SMALL = 0x0;
- const int ICON_BIG = 0x1;
-
- [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- extern static IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
-
- static IntPtr hProcess
- {
- get { return Process.GetCurrentProcess().MainWindowHandle; }
- }
-
-
- static void CreateShortcut(string targetPath, string shortcutPath)
- {
- // 创建 WshShell 对象
- WshShell shell = new WshShell();
-
- // 创建快捷方式对象
- IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
-
- // 设置目标路径和其他属性
- shortcut.TargetPath = targetPath;
- shortcut.WorkingDirectory = System.IO.Path.GetDirectoryName(targetPath);
- shortcut.Description = "Shortcut Description";
- shortcut.Save();
-
- string exeFilePath = Assembly.GetEntryAssembly().Location;
- string iconPath = Path.ChangeExtension(exeFilePath, ".ico");
-
- SetShortcutIcon(shortcutPath, iconPath);
- }
-
- static void SetShortcutIcon(string shortcutPath, string iconPath)
- {
- // 创建 WshShell 对象
- WshShell shell = new WshShell();
-
- // 读取快捷方式对象
- IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
-
- // 设置图标路径
- shortcut.IconLocation = iconPath;
-
- // 保存快捷方式
- shortcut.Save();
- }
- }
-