1

Background

I have a C# windows Form application that sets its default top and left value based on the top and left value of the previous instance of the app opened.

For example, app A opens at left=50 and top=15. User drags the application window to the right so that the app's left=500 and top=50. User exits the application and reopens the application. Its current position is at the position it was last closed (left=500 and top=50).

Problem

I want to reset the value to left=50 and top=15 after I have restarted the Windows OS. Googling only came out with resetting the values after application quits but what I want is resetting the values after Windows OS restart.

The only way I can think of currently is creating a task in task scheduler that runs a batch script file to adjust the values in .config file of the app after windows restart but doing it this way would require one to maintain an extra script file and create a task (more work).

John Evans Solachuk
  • 1,953
  • 5
  • 31
  • 67
  • 1
    If you create a volatile key (via `REG_OPTION_VOLATILE`) in the current user registry, it will disappear when the user logs out. I believe that will include system restarts. – Harry Johnston May 23 '17 at 03:41

2 Answers2

1

Do you control the source code? If yes, start doing this after the startup logic has run once:

On resize event, If the new size is not maximized then store the new size into either the registry or into a config file in Users > (this user) > Appdata > Local > (your company) > (your application)

If a form is just moved and not resized, see this: C# Form Move Stopped Event

At app startup, if this value exists and if it is appropriate for the current screen resolution then use it.

Dave S
  • 1,427
  • 1
  • 16
  • 18
1

The alternative way is to detect that Windows was restarted since the last application launch and to reset settings accordingly.

The simplistic solution is to store an additional setting, say LastLaunchTime, and set it to the current time on application start.

Then you can compare it with a startup time and figure out if the system was restarted since the last launch:

DateTime startupTime = DateTime.Now - UpTime;
if(Settings.LastLaunchTime < startupTime) {
    //system was restarted since the last launch, resetting location
}
Settings.LastLaunchTime = DateTime.Now;

//System up time property
TimeSpan UpTime {
    get {
        using (var uptime = new PerformanceCounter("System", "System Up Time")) {
            uptime.NextValue();       //Call this an extra time before reading its value
            return TimeSpan.FromSeconds(uptime.NextValue());
        }
    }
}

System uptime calculation was taken from here: Retrieve system uptime using C#

default locale
  • 13,035
  • 13
  • 56
  • 62