Codigos Fonte, Artigos e Dicas
Singleton em C#
Se vc quer fazer que sua aplicação rode apenas uma vez, ou seja, se o (burro) usuario clicar mais de uma vez no icone, só vai abrir uma aplicação, e nao 2 ou 3.
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
public static void HandleRunningInstance(Process instance)
{
//Make sure the window is not minimized or maximized
ShowWindowAsync (instance.MainWindowHandle , WS_SHOWNORMAL);
//Set the real intance to foreground window
SetForegroundWindow (instance.MainWindowHandle);
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(
IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")] private static extern bool
SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
[STAThread]
static void Main()
{
//Get the running instance.
Process instance = RunningInstance();
if (instance == null)
{
//There isn't another instance, show our form.
Application.Run (new frmLogin());
}
else
{
//There is another instance of this process.
HandleRunningInstance(instance);
}
}
aplique isso a sua aplicação e terá sucesso…
Nenhum post foi relacionado a este
| Imprimir artigo | Este artigo foi escrito por paulodiogo em 22 22UTC junho 22UTC 2009 às 11:43, e está arquivado em Design Pattern. Siga quaisquer respostas a este artigo através do RSS 2.0. Você pode deixar uma resposta ou fazer um trackback do seu próprio site. |

há 1 ano atrás
Perfeito!
[Reply]