我正在开发一个Windows应用程序,我想将此应用程序设置为Windows启动应用程序,我使用此代码: -
public static void SetStartup(string AppName,
bool enable)
{
try
{
string runKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey);
if (enable)
{
if (startupKey.GetValue(AppName) == null)
{
startupKey.Close();
startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
startupKey.SetValue(AppName, Assembly.GetExecutingAssembly().Location + " /StartMinimized");
startupKey.Close();
}
}
else
{
startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
startupKey.DeleteValue(AppName, false);
startupKey.Close();
}
}
catch
{
}
}
SetStartup(Application.ExecutablePath, true);
此代码工作正常。它将应用程序设置为启动应用程序。 我检查在运行窗口中执行msconfig命令。它显示在启动选项卡中检查了此应用程序。但是当我重新启动系统时它不启动应用程序。 任何人都可以告诉我问题是什么,我该如何解决这个问题。
答案 0 :(得分:2)
如果一切都指向它处于启动状态,那么我只能假设它的一部分是正确的,但应用程序由于某种原因无法启动。
在运行时启动应用程序时,它的工作目录设置为C:\ Windows \ System32
我遇到了可能在其主目录中查找文件的应用程序的问题,例如配置文件,但无法找到它们。
通常,无论如何都会找到以正常方式引用的文件,但如果您在代码中手动指定路径,则可以使用:
string pathToDLL = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LibraryFile.dll");
使用AppDomain.CurrentDomain.BaseDirectory应该提供应用程序exe的路径,而不是工作目录。
这可能是问题的原因吗?
此外,我将假设Vista向上是操作系统,如果是这种情况,那么您的应用程序必须以提升的速度运行才能写入该注册表。因此,如果UAC关闭并且机器重新启动,那么您的应用程序(如果它在清单中设置为以requireAdministrator运行)将无声地失败。
马丁
答案 1 :(得分:1)
最后我得到了这个问题的答案。使用StreamWriter创建应用程序的URL链接,而不是在启动文件夹中创建LNK。
private void appShortcutToStartup()
{
string linkName ="MytestLink";
string startDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (!System.IO.File.Exists(startDir + "\\" + linkName + ".url"))
{
using (StreamWriter writer = new StreamWriter(startDir + "\\" + linkName + ".url"))
{
string app = System.Reflection.Assembly.GetExecutingAssembly().Location;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = Application.StartupPath + "\\backup (3).ico";
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
}
private void delappShortcutFromStartup()
{
string linkName ="MytestLink";
string startDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (System.IO.File.Exists(startDir + "\\" + linkName + ".url"))
{
System.IO.File.Delete(startDir + "\\" + linkName + ".url");
}
}
此代码非常正常。
答案 2 :(得分:0)
我认为最简单的方法是遵循以下步骤
1。)构建应用程序
2.)导航到调试文件夹
3)复制exe并将其放在启动位置
**C:\Documents and Settings\user\Start Menu\Programs\Startup**
OR
只需将你的exe拖到开始菜单 - >程序 - >启动并粘贴它(即 释放鼠标按钮)
我想这会做你的工作
希望有所帮助