changing the system time format on windows 7 - c#

Well I am looking for a method to change the default windows 7 time format for a system.
So if a system uses like 10PM or 10 AM as default time notation, then i like to change that system to 10:00 or 22:00.
I know how to do it through the GUI, but in my case our software (C#) has to check if time notation is OK and if it is not change it by usage of
C#, registry editing, vbscript, commanline or Powershell, or some specific .exe file
The software we wrote allready makes usage of external progs / languages (vbscript/powershell).
But the problem is so far i have not found a method to do this other then taking over a remote screen.
Perhaps someone knows how to do this ?
The same counts for time zone, and date notation.

You may change the system time format using following code:
RegistryKey rk = Registry.CurrentUser.OpenSubKey(#"Control Panel\International", true);
rk.SetValue("sTimeFormat", "hh:mm:ss"); // HH for 24hrs, hh for 12 hrs
But IMO, this would not be a good practice for an application to change the system user's settings without the consent of the user.

I found this link that shows it being done via vb.net but you would have to translate it. or you could compile this to an exe and run it from a shell. http://www.access-programmers.co.uk/forums/showthread.php?t=152624

The property way to do this in .NET is with code such as the following:
CultureInfo newCultureInfo = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCultureInfo.DateTimeFormat.ShortDatePattern = shortDateFormat;
newCultureInfo.DateTimeFormat.LongTimePattern = longTimeFormat;
Thread.CurrentThread.CurrentCulture = newCultureInfo;

Regarding the solution using the "Control Panel\International" registry key (sorry, can't comment due to not have a 50 reputation):
This doesn't appear to affect the existing process, only new processes created after changing the registry. And obviously code assuming registry values (i.e. implementation details) could break in a future version of windows.
Also the code should Dispose the RegistryKey object. It would be better written with a using block.
Regarding if you should do this, while it would be unlikely an app would want to change the time date format (maybe an app that's an improved way of setting system info), it would be very reasonable to need to do this in an automated test. It's a common bug for code to depend on the default time/date format, so setting them to non-default values, or testing code with various time/date formats could be a good idea.

Related

How to refesh short time string (C# DateTime.Now)?

I'm making a Notepad program with Windows Form and having a problem with the Date/Time feature:
My system time and date format (short) are hh:mm tt M/d/yyyy. When I press F5 (Date/Time feature) in Notepad, it add a time string with format like above. Then I change the system time and date format to HH:mm dd-MMM-YY and press F5 again in Notepad, it add another time string with the format I've changed.
But with my Notepad project (I use DateTime.Now.ToShortTimeString() and DateTime.Now.ToShortDateString() to do this feature), I have to start the program again if I want the format to take effect in my program, otherwise it will use the first format no matter how many times I press F5.
So I want to ask if there is a way to fix this.
I'm using VS 2013.
Very good question. The date is formatted according to current user culture information, but the information is cached by .NET. What you need to do is force .NET to clear the cache by calling CultureInfo.ClearCachedData method beforehand.
More information here: https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.clearcacheddata(v=vs.80).aspx
Please also note, that clearing the cache every time a user wants to insert Date & Time is somehow missing the point of caching (OK, I am exaggerating a little bit). What you can do is only clear the cache, when the system tells you that its configuration has changed. You do this by listening to SystemEvents.UserPreferenceChanged event. More information in answer here: How to receive event when user changes system's culture
See SystemEvents class, UserPreferenceChang* events.

Running Excel in a different locale/Change system locale settings

I'm trying to find a way to change the locale settings when opening Excel, or changing the entire system locale settings.
I know it's bad practice to do this, so I'll just note that this is purely for automated testing reasons. We want to run our Excel add-in simulating multiple different locale settings to make sure it's handling all the functions properly (if there's a better way of doing this than changing settings please let me know!)
I know how to change the CurrentCulture of the thread, but that only seems to apply to our add-in, so functions of Excel called by our add-in run with the system locale settings.
There are 3 ways I've found that I thought might get this working, but one of them seems like an insanely bad idea, and the other two I can't manage to get working:
The really bad one was to import a .reg file in to the system registry before opening Excel, but I don't like the idea of this.
Another way seems to be to use SetLocaleInfo, imported from kernel32.dll, but for the life of me I can't figure out the parameters to use, or even if this is what I need.
The last way was to use Microsofts AppLocale tool, but opening it through that with different language settings didn't seem to achieve what I expected. Actually, it didn't seem to change anything at all from my current system settings!
If anyone can provide any help it would be greatly appreciated, otherwise I guess these are just being left as manual tests!
I would suggest creating several users on your computer and adjusting user locale settings accordingly to your test purposes for each user in Control Panel -> Region and Language. This basically allows setting a default language, and currency/number/date/time formats. If this is what you want, you can launch excel using a different user execution context by either runas command, which requires a manual password entering, or in batch mode using psexec tool from SysInternals: http://technet.microsoft.com/en-us/sysinternals/bb897553
Make sure to specifycommand line options that load account's profile. Unfortumnately you can only adjust user locale settings per each user. System locale settings are defined per computer.
Here you have a full example of how to call SetLocaleInfo from .Net. I won't copy here for brevity, it's a
http://took1.googlecode.com/svn-history/r87/trunk/Code/App.Dev/SetLocale.cs

Get last exe file Execution Date (or Time) in Windows using .NET or VB6

Basically, I wouldn't find this anywhere. All I really need is date last executed, or even date last shutdown (that is, exe ended execution). I don't even need a catalog of all runs/shutdowns, just the last one.
I'm sure they must keep it somewhere. Reason being, in control panel (Win Vista) when you go to "programs & features" you have the option to sort the programs by how often they are used (which is run/executed) since this will not be based on last accessed time. Then, in their description, they quote usage frequency with terms such as "rarely", "sometimes", "often", "regularly" etc...
Now in Win7, if you right click on the columns & select "more..." from the installed programs listing control, you'll see a "Last Used On" option! This implies that last used date is at least kept somewhere in Win7.
Any ideas anyone?
Update: About LastAccess DateTime: LastAccess is too unreliable it seems (correct me if i'm wrong) it keeps on changing as soon as something (such as windows) accesses it. Maybe i should ask, does windows mess this field up by accessing the file to read info out of it (such as file size/dates etc) especially when browsing folders or does windows access files secretly to prevent contaminating the last access dates?
UPDATE 2
This is apparently different for MSI installations.
Information got from this thread (last post):
http://www.tomshardware.co.uk/forum/55552-45-remove-program-date
For an MSI installation Windows Installer maintains a usage count in its own registry > >based on Product and Feature, which can be found for example under
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products\\Usage
This is maintained by the Windows Installer API.
MsiUseFeature() increments the usage counter (http://msdn.microsoft.com/en-us/library/aa370502(VS.85).aspx)
MsiGetFeatureUsage() gets the Last Used Date and the Use Count
The usage counter is also incremented when launching an application via an advertised shortcut or when using one of the MsiProvide*() functions.
UPDATE
Check out this article:
http://blogs.msdn.com/b/oldnewthing/archive/2004/07/09/178342.aspx
It seems like those values aren't stored anywhere, but more like an assumtion. So you might aswell use the File.GetLastAccessTime to get this.
You could also use a FileSystemWatcher and Process. Then set a flag when the FileSystemWatcher sees a change and the exe is started.

Confirming system time

I'm trying to make a system that basically allows me to shove a DLL in an installation and some code in an exe that allows me to release all of my future programs as beta releases for a while.
Now the problem is of course if I'd want to do that, i'd need to choose until when the program is valid. Which is fine, except that by changing your system clock, you can easily bypass the system.
Now, I'd like to hear what people generally do for something like this.
I've been trying a few approaches such as contacting a site to give the timestamp and compare that, which would be fine if it didn't always increase the program start time by over 9000
and and the fact that people would then not be able to use it if they're not connected to the internet.
Any suggestions are much appreciated.
This is not 100% guaranteed solution but it will take you there
You will need to implement these things in the config file (Why Config file, because if user deletes it your app won't run). Also encrypt all the following data.
Store the Date and Time on which application ran.
Store the exact amount of time for which application ran.
By doing so you can avoid:
If user change the computer time, you will come to know that, as your app is logging Date and Time, it might overlap the earlier time, say user ran app on 6th and 10th of month, and then he reverts date to 7th, you will come to know about it.
Secondly user can change the date on every run to single date, in that case the total duration used will help you. Say user set date to 1st of month every time he runs it, in that case, he can use app for 24 Hrs only not more than that.
Other options like
Checking time from External Server (Flaw: Requires internet access)
Storing Time in Registry (Flaw: User can easily manipulate registry)
Hope this helps you.
If your software can access some network share on some local server/nas, you can create a new file on this network share, and this file will have a creation time set using the clock of the server/nas, so you can compare the time set on the server/nas to the time of the local computer.
Or you can also save somewhere (a file, in the registry, in a DB) the last time of the last execution, and if the clock go back in time, then you can lock the application and require further assistance :-)

How can I change a Windows user's regional settings/date format?

I use a VB6/COM+ application which outputs date/time values based on the short date settings in the Control Panel, Regional Settings, for the user that runs it. The program that then parses that output has a configurable setting for the date format it expects, and presents in the UI.
e.g. If the regional setting for the user is set to mm/dd/yyyy, and it outputs 06/18/2009, the application expecting "18/06/2009" fails with "String was not recognized as a valid DateTime".
As we usually run this application as a service account, which we have not logged in as interactively to create a profile, we generally set the correct date format and then tick the "Apply all settings to the current user account and the default user profile" option.
I would like to be make the C# configuration utility I have written for this mess to be able to set the date format programmatically for a given user.
Edit
I would like nothing more than to change the code, but do not have the ability to do so at this time.
I also know that what I am asking is a bad thing to do. With regards to "it should be the user's choice" - I am that user, as I create it explicitly for the task; I just want to set the date format by a scripted method, rather than having to do the clicking myself.
This is specifically discouraged by Microsoft. Any solution you may come up with will be a filthy hack that will probably stop working soon.
Think of it this way: who are you to decide those settings? Don't you think that's the user's decision?
Back on topic: find an unambiguous format for the applications to communicate in, such as YYYYMMDD. The application that displays can then simply respect the actual user settings, as it should.
But, since you can't change it, just poke into the registry:
Current user:
HKEY_CURRENT_USER\Control Panel\International
Specific user:
HKEY_USERS\(user SID)\Control Panel\International
Default user:
HKEY_USERS\.DEFAULT\Control Panel\International
sShortDate is probably the value you want to change.
If you are going to modify the profile to suit your needs, why not just ignore the profile settings and hardcode the format you want in your app?
code:
Imports System.Threading
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US", False)
Microsoft.Win32.Registry.SetValue("HKEY_CURRENT_USER\Control Panel\International", "sShortDate", "M/d/yyyy")
While persistently changing a user's culture (regional settings) is to be done cautiously, there are legitimate use cases.
On Windows 8 and Windows Server 2012 and above, Windows PowerShell comes with the
Set-Culture cmdlet, which is the programmatic equivalent of choosing a different region via Control Panel (intl.cpl).
For instance, Set-Culture fr-CA is the equivalent of interactively choosing region French (Canada) for the current user.
Caveat: Mixed cultures such as en-DE (sic) appear not to work as of Windows PowerShell v5.1 - see this answer of mine.
While it won't be fast, it is possible to call PowerShell commands from C#.

Categories

Resources