Frage

my app was working ok and it would execute on startup before. I added a notify icon and in my code,there are some places that this icon changes.I added all required icons in the root folder of my app,and everything is working fine with the icons,except the startup boot of my app. I can see my app's address in the "run" part of the registry(I mean everything is the same as when my app booted at startup properly).but my app won't run at startup anymore. any advice on my matter? PS:I thought I should explain my work a little bit and I wrote a little piece of app that has the exact same problem

    public Icon[] icons = new Icon[2] { new Icon("icon1.ico"), new Icon("icon2.ico") };
    public int counter = 0;


    private void button1_Click(object sender, EventArgs e)
    {
        notifyIcon1.Visible = true;
        timer1.Start();

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter %= 2;
        notifyIcon1.Icon = icons[counter];
        counter++;

As you can see,the app changes the icon of the notifyicon in every tick.with this code,the app won't run at startup.but if I remove the iconchanging feature of the app,it will actually run at startup

War es hilfreich?

Lösung

This requires psychic debugging, I'll guess that you are loading these icons using their relative path name. Something like new Icon("foo.ico").

This can only work correctly if the default working directory of your program is set where you hope it will be. It usually is, certainly when you start your program from Visual Studio or start it from a desktop shortcut. But not when you added it to the Run registry key. Environment.CurrentDirectory will be set elsewhere, typically the Windows directory.

You must always use the full path name of files. An easy way to get that path is:

    var home = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
    var path = System.IO.Path.Combine(home, "foo.ico");
    var icon = new Icon(path);

But there's certainly a better way than storing icons as files, you can embed them in your program. Project + Properties, Resources tab. Click the arrow on the Add Resource button, Add Existing File and navigate to your .ico file. Now the icon is embedded in your program, you'll never lose track of it and can't forget to copy it when you deploy your program on another machine. And the code is simpler as well:

    var icon = Properties.Resources.foo;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top