Skip to content

Commit 98c09d2

Browse files
authored
Merge pull request #8 from nikeee/patch-1
Add Winforms Sample
2 parents d1348f9 + 897e375 commit 98c09d2

1 file changed

Lines changed: 49 additions & 6 deletions

File tree

README.md

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,26 @@ For single instance applications on .NET Core
44
NuGet Package: https://www.nuget.org/packages/SingleInstanceCore/
55
# Usage
66

7-
Note: Usage examples are for WPF desktop applications. For other platforms/frameworks, inheritance and initialization should be done accordingly, not exactly like the examples.
7+
Note: Usage examples are for WPF and Winforms desktop applications. For other platforms/frameworks, inheritance and initialization should be done accordingly, not exactly like the examples.
88

99
The class that handles instance invokation should inherit ISingleInstance and implement OnInstanceInvoked method.
1010

11-
E.g. in App class (App.xaml.cs):
11+
## WPF
12+
E.g. in App class (`App.xaml.cs`):
1213
```csharp
1314
public partial class App : Application, ISingleInstance
1415
{
1516
public void OnInstanceInvoked(string[] args)
1617
{
17-
//What to do with the args another instance has sent
18+
// What to do with the args another instance has sent
1819
}
19-
...
20+
// ...
2021
}
2122
```
2223
Initialization of instance should be done when application is starting, and cleanup method should be called on the exit point of the application.
2324

24-
E.g. in App class (App.xaml.cs):
25+
E.g. in App class (`App.xaml.cs`):
2526
```csharp
26-
2727
private void Application_Startup(object sender, StartupEventArgs e)
2828
{
2929
bool isFirstInstance = this.InitializeAsFirstInstance("soheilkd_ExampleIPC");
@@ -42,3 +42,46 @@ E.g. in App class (App.xaml.cs):
4242
SingleInstance.Cleanup();
4343
}
4444
```
45+
46+
## Winforms
47+
Winforms doesn't have an Application.cs that could implement the `ISingleInstance` interface. We have to define one ourselves.
48+
```csharp
49+
static class Program
50+
{
51+
[STAThread]
52+
static void Main(string[] args)
53+
{
54+
var app = new YourApplication();
55+
56+
var isFirstInstance = app.InitializeAsFirstInstance(nameof(YourApplication));
57+
if (isFirstInstance)
58+
{
59+
try
60+
{
61+
app.Run();
62+
}
63+
finally
64+
{
65+
SingleInstance.Cleanup();
66+
}
67+
}
68+
}
69+
}
70+
71+
class YourApplication : ISingleInstance
72+
{
73+
public void Run()
74+
{
75+
Application.SetHighDpiMode(HighDpiMode.SystemAware);
76+
Application.EnableVisualStyles();
77+
Application.SetCompatibleTextRenderingDefault(false);
78+
Application.Run(new MainForm()); // Blocks until the main window is closed
79+
}
80+
81+
public void OnInstanceInvoked(string[] args)
82+
{
83+
// What to do with the args another instance has sent
84+
}
85+
}
86+
87+
```

0 commit comments

Comments
 (0)