Ok, I have a code that I only want to use for the first form1 load, so that means never use it agian.
So how do I use a code once then never use it again?
Ok, I have a code that I only want to use for the first form1 load, so that means never use it agian.
So how do I use a code once then never use it again?
Two different meanings of "only the first time" matter: once during the current process, or once ever across future launches/installs. pointed toward persisting a flag, and suggested an in-memory flag. Both are valid — pick the approach below that matches what you really need.
For "once per process" (run once while the app is running)
Example (thread-safe, process-lifetime guard):
using System.Threading;
static int _ranOnce;
private void Form1_Shown(object sender, EventArgs e)
{
if (Interlocked.Exchange(ref _ranOnce, 1) == 0)
{
// one-time code here
}
} For "once ever" (persist across future launches)
Example (file marker in LocalApplicationData):
var folder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"MyCompany", "MyApp"
);
Directory.CreateDirectory(folder);
var flagFile = Path.Combine(folder, "first_run.flag");
if (!File.Exists(flagFile))
{
// first-run code
File.WriteAllText(flagFile, DateTime.UtcNow.ToString("o"));
} Notes and pitfalls
Jump to Post— CanYouHandstand 0Do you mean never use it again while the application is running? Or never use it when the application is run in the future?
If it is the latter, you could add a bool flag to your projects Properties Settings.settings which is initialised to false. Upon entering form1_Load for …
Do you mean never use it again while the application is running? Or never use it when the application is run in the future?
If it is the latter, you could add a bool flag to your projects Properties Settings.settings which is initialised to false. Upon entering form1_Load for the first time, the flag would be checked to ensure it is false, allowing the code to execute. The flag is then updated inhibiting it from the code being executed in the future.
Cameron
Declare a Boolean static field.
public class Form1 : ....
{
static bool flag=true;
void form1_load(...) {
if(flag) {
....
flag=false;
}
}
} We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.