Reputation: 15807
Hi,
Say that we got a WinForm application(app1) running in the background, now another application(app2)(the topmost active application) trigger a startProcess with the app1.
Now I need app1 to use the existing instance and bring it to topmost application(not only within the app1 application).
I have found this : http://sanity-free.org/143/csharp_dotnet_single_instance_application.html
Is it true that its not possible to do this without API? I have looked att bringToFront, Activate and Focus but all these does seem to only effect within a application and not between applications?
Upvotes: 0
Views: 1721
Reputation: 6689
I don't know what you mean "without API" or why that matters.
However the simplest way is via WindowsFormsApplicationBase
. It gives you all you need, with just a few lines of code.
You need to add a reference to the Microsoft.VisualBasic
assembly - but it can be used through C#.
Make this class:
public class SingleInstanceApplication : WindowsFormsApplicationBase
{
private SingleInstanceApplication()
{
IsSingleInstance = true;
}
public static void Run(Form form)
{
var app = new SingleInstanceApplication
{
MainForm = form
};
app.StartupNextInstance += (s, e) => e.BringToForeground = true;
app.Run(Environment.GetCommandLineArgs());
}
}
And in your Program.cs, change the run line to use it:
//Application.Run(new Form1());
SingleInstanceApplication.Run(new Form1());
Upvotes: 2
Reputation: 1442
You really need some sort of communications between 2 apps. In article link to you posted communications is through WinApi messages. Also you can do that through sockets or through files and FileWatchers.
UPD1: Code to simulate minimize with timer simulation message from another app and maximize on that message:
public partial class Form1 : Form
{
private Timer _timer = null;
public Form1()
{
InitializeComponent();
this.Load += OnFormLoad;
}
private void OnFormLoad(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Hide and top most on timer";
btn.Width = 200;
btn.Click += OnButtonClick;
this.Controls.Add(btn);
}
private void OnButtonClick(object sender, EventArgs e)
{
//minimize app to task bar
WindowState = FormWindowState.Minimized;
//timer to simulate message from another app
_timer = new Timer();
//time after wich form will be maximize
_timer.Interval = 2000;
_timer.Tick += new EventHandler(OnTimerTick);
_timer.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
_timer.Stop();
//message from another app came - we should
WindowState = FormWindowState.Normal;
TopMost = true;
}
}
Upvotes: 0