|
<< Click to Display Table of Contents >> Uma instância |
![]() ![]()
|
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
static class Program
{
// chamadas as dlls
public const Int32 NATIVE_ERROR_ALREADY_EXISTS = 183;
[DllImport("coredll.dll", EntryPoint = "CreateMutex", SetLastError = true)]
public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool InitialOwner, string MutexName);
[DllImport("coredll.dll", EntryPoint = "ReleaseMutex", SetLastError = true)]
public static extern bool ReleaseMutex(IntPtr hMutex);
[DllImport("coredll.dll")]
private static extern IntPtr FindWindow(IntPtr className, string windowName);
[DllImport("coredll.dll")]
internal static extern int SetForegroundWindow(IntPtr hWnd);
[DllImport("coredll.dll")]
private static extern bool SetWindowPos(IntPtr hwnd, int hwnd2, int x, int y, int cx, int cy, int uFlags);
[MTAThread]
static void Main()
{
// se tem uma instancia rodando...
if (IsInstanceRunning())
{
// procura tela de "consulta"
IntPtr h = FindWindow(IntPtr.Zero, "Consulta");
// não achou?, procura tela de cadastro
if (h == IntPtr.Zero)
h = FindWindow(IntPtr.Zero, "Cadastrar conta");
// não achou ainda?, procura tela de edição
if (h == IntPtr.Zero)
h = FindWindow(IntPtr.Zero, "Editando conta");
// achou, manda o foco
SetForegroundWindow(h);
SetWindowPos(h, 0, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, 0x0040);
return;
}
else
{
// roda normalmente
Application.Run(new Cadastro());
}
}
// aqui cria-se um mutex para impedir mais de um
public static bool IsInstanceRunning()
{
// cria um mutex
IntPtr hMutex = CreateMutex(IntPtr.Zero, true, "HoneyMobile");
// mutex não foi criado?
if (hMutex == IntPtr.Zero)
throw new ApplicationException("Erro ao criar mutex: " + Marshal.GetLastWin32Error().ToString("X"));
// se o ultimo erro for diferente de "ja existe"...
return (Marshal.GetLastWin32Error() == NATIVE_ERROR_ALREADY_EXISTS);
}
}