IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Windows Forms Discussion :

ouvrir mon application en cours si on essaie de la lancer une seconde fois


Sujet :

Windows Forms

  1. #1
    Membre éprouvé

    Homme Profil pro
    kiné passionné de dev
    Inscrit en
    Mars 2006
    Messages
    1 570
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : kiné passionné de dev

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 570
    Billets dans le blog
    1
    Par défaut ouvrir mon application en cours si on essaie de la lancer une seconde fois
    Bonjour,

    je vais essayer d'être plus clair que mon titre:
    Ce que je veux:
    -l'utilisateur lance mon application, il l'utilise, là ok
    -l'utilisateur a oublié qu'il a déjà lancé mon application, il essai de la lancer une deuxième foi, là j'ai l'application qui vérifie si elle n'est pas déjà lancée:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Dim Proc_EnCours As Process = Process.GetCurrentProcess
            Dim Les_Proc() As Process = Process.GetProcesses()
            For Each processus As Process In Les_Proc
                'Il ne faut pas comparer par rapport à cette instance
                'du programme mais une autre (grâce à l'ID)
                If Not Proc_EnCours.Id = processus.Id Then
                    'Si les ID sont différents mais de même nom ==> 2 fois le même programme
                    If Proc_EnCours.ProcessName = processus.ProcessName Then
     
                        MessageBox.Show("Le programme ne peut pas être lancé 2 fois!")
                        Application.Exit()
                    End If
                End If
            Next
    Jusque là tout va bien, mais à présent ce que je voudrais, c'est envoyer un truc, je ne sais pas quoi à la première instance, pour qu'elle ouvre la fenetre principale, comme outlook en fait.
    Cordialement

  2. #2
    Expert confirmé
    Avatar de smyley
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    6 270
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 6 270

  3. #3
    Membre éprouvé

    Homme Profil pro
    kiné passionné de dev
    Inscrit en
    Mars 2006
    Messages
    1 570
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : kiné passionné de dev

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 570
    Billets dans le blog
    1
    Par défaut
    je m'y penche dès que possible.

  4. #4
    Membre éprouvé

    Homme Profil pro
    kiné passionné de dev
    Inscrit en
    Mars 2006
    Messages
    1 570
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : kiné passionné de dev

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 570
    Billets dans le blog
    1
    Par défaut
    J'ai regardé ce que tu m'as donné, rien ne convient.
    Mais j'ai trouvé un truc plutôt interressant:
    L'événement StartupNextInstance

    Mais j'ai un problème, c'est que je n'arrive pas à m'en servir, j'explique:

    je démarra mon application par Sub Main. et j'ai l'impression qu'il faut que Startupnextinstance se trouve dans myapplicationevents.vb
    Le code du gestionnaire d'événements StartupNextInstance est stocké dans le fichier ApplicationEvents.vb, qui est masqué par défaut.
    . Ce qui ne convient pas.

    J'ai lu aussi que si on démarrait pas une Sub Main, il fallait que la classe qui contient Sub Main hérite de "WindowsFormsApplicationBase", ce que j'ai fait, mais rien n'y fait.

    Quand je démarre mon application la première fois, elle se démarre, et quand j'en ouvre ne seconde, elle s'ouvre normalement (comme si ce n'était pas une application single instance). pourtant, j'ai modifié Application.myapp pour avoir
    Code XML : Sélectionner tout - Visualiser dans une fenêtre à part
    <SingleInstance>true</SingleInstance>

  5. #5
    Expert confirmé
    Avatar de smyley
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    6 270
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 6 270
    Par défaut
    Tu es sur que tu as bien regarder https://secure.codeproject.com/KB/vb...&select=228488 ?
    Parce que le but de ce code est justement de copier les arguments passés à la nouvelle instance vers l'ancienne ...

    Sinon si tu n'en veux vraiment pas il y a le code que j'utilise dans DreamShield (en C# ...) :
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
     
    public delegate void NewInstanceMessageEventHandler(object sender, object message);
     
        public class SingleInstanceApplication
        {
            //win32 translation of APIs, message constants and structures
            private class NativeMethods
            {
                [DllImport("user32.dll")]
                public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
                [DllImport("user32.dll")]
                public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
     
                public const short WM_COPYDATA = 74;
     
                public struct COPYDATASTRUCT
                {
                    public int dwData;
                    public int cbData;
                    public IntPtr lpData;
                }
            }
     
            //a utility window to communicate between application instances
            private class SIANativeWindow : NativeWindow
            {
                public SIANativeWindow()
                {
                    CreateParams cp = new CreateParams();
                    cp.Caption = _theInstance._id; //The window title is the same as the Id
                    CreateHandle(cp);
                }
     
                //The window procedure that handles notifications from new application instances
                protected override void WndProc(ref Message m)
                {
                    if (m.Msg == NativeMethods.WM_COPYDATA)
                    {
                        //convert the message LParam to the WM_COPYDATA structure
                        NativeMethods.COPYDATASTRUCT data = (NativeMethods.COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(NativeMethods.COPYDATASTRUCT));
                        object obj = null;
                        if (data.cbData > 0 && data.lpData != IntPtr.Zero)
                        {
                            //copy the native byte array to a .net byte array
                            byte[] buffer = new byte[data.cbData];
                            Marshal.Copy(data.lpData, buffer, 0, buffer.Length);
                            //deserialize the buffer to a new object
                            obj = Deserialize(buffer);
                        }
                        _theInstance.OnNewInstanceMessage(obj);
                    }
                    else
                        base.WndProc(ref m);
                }
            }
     
            //Singleton 
            static SingleInstanceApplication _theInstance = new SingleInstanceApplication();
     
            //this is a uniqe id used to identify the application
            string _id;
            //The is a named mutex used to determine if another application instance already exists
            Mutex _instanceCounter;
            //Is this the first instance?
            bool _firstInstance;
            //Utility window for communication between apps
            SIANativeWindow _notifcationWindow;
     
            private void Dispose()
            {
                //release the mutex handle
                _instanceCounter.Close();
                //and destroy the window
                if (_notifcationWindow != null)
                    _notifcationWindow.DestroyHandle();
            }
     
            private void Init()
            {
                _notifcationWindow = new SIANativeWindow();
            }
     
            //returns a uniqe Id representing the application. This is basically the name of the .exe 
            private static string GetAppId()
            {
                #warning SingleInstance Handler Customisé avec un Guid
                return "{107746EE-AD4B-4e7b-B209-CF7F1A93F631}";
            }
     
            //notify event handler
            private void OnNewInstanceMessage(object message)
            {
                if (NewInstanceMessage != null)
                    NewInstanceMessage(this, message);
            }
     
            private SingleInstanceApplication()
            {
                //AUDREY
                //_id = "SIA_" + GetAppId();
                _id = "SIA_" + GetAppId();
                _instanceCounter = new Mutex(false, _id, out _firstInstance);
            }
     
            private bool Exists
            {
                get
                {
                    return !_firstInstance;
                }
            }
     
            //send a notification to the already existing instance that a new instance was started
            private bool NotifyPreviousInstance(object message)
            {
                //First, find the window of the previous instance
                IntPtr handle = NativeMethods.FindWindow(null, _id);
                if (handle != IntPtr.Zero)
                {
                    //create a GCHandle to hold the serialized object. 
                    GCHandle bufferHandle = new GCHandle();
                    try
                    {
                        byte[] buffer;
                        NativeMethods.COPYDATASTRUCT data = new NativeMethods.COPYDATASTRUCT();
                        if (message != null)
                        {
                            //serialize the object into a byte array
                            buffer = Serialize(message);
                            //pin the byte array in memory
                            bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
     
                            data.dwData = 0;
                            data.cbData = buffer.Length;
                            //get the address of the pinned buffer
                            data.lpData = bufferHandle.AddrOfPinnedObject();
                        }
     
                        GCHandle dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                        try
                        {
                            NativeMethods.SendMessage(handle, NativeMethods.WM_COPYDATA, IntPtr.Zero, dataHandle.AddrOfPinnedObject());
                            return true;
                        }
                        finally
                        {
                            dataHandle.Free();
                        }
                    }
                    finally
                    {
                        if (bufferHandle.IsAllocated)
                            bufferHandle.Free();
                    }
                }
                return false;
            }
     
            //2 utility methods for object serialization\deserialization
            private static object Deserialize(byte[] buffer)
            {
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    return new BinaryFormatter().Deserialize(stream);
                }
            }
     
            private static byte[] Serialize(Object obj)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    new BinaryFormatter().Serialize(stream, obj);
                    return stream.ToArray();
                }
            }
     
            public static bool AlreadyExists
            {
                get
                {
                    return _theInstance.Exists;
                }
            }
     
            public static bool NotifyExistingInstance(object message)
            {
                if (_theInstance.Exists)
                {
                    return _theInstance.NotifyPreviousInstance(message);
                }
                return false;
            }
     
            public static bool NotifyExistingInstance()
            {
                return NotifyExistingInstance(null);
            }
     
            public static void Initialize()
            {
                _theInstance.Init();
            }
     
            public static void Close()
            {
                _theInstance.Dispose();
            }
     
            public static event NewInstanceMessageEventHandler NewInstanceMessage;
        }

    et ça s'utilise comme suit :
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
     
    [STAThread]
            public static MainForm form = null;
     
            static void Main(string[] args)
            {
                ...
     
                if (SingleInstanceApplication.AlreadyExists &&
                    SingleInstanceApplication.NotifyExistingInstance(args))
                    return;
                SingleInstanceApplication.Initialize();
                SingleInstanceApplication.NewInstanceMessage += new NewInstanceMessageEventHandler(SingleInstanceApplication_NewInstanceMessage);
                try
                {
                    form = new MainForm(args);
                }
                finally
                {
                    SingleInstanceApplication.Close();
                }
     
                ...
            }
     
            static void SingleInstanceApplication_NewInstanceMessage(object sender, object message)
            {
                string[] args = null;
                try
                {
                    args = (string[])message;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format("Erreur interne, impossible de récupérer les arguments d\'instance\n{0}",
                        ex), "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
     
                if (args != null && form != null)
                {
                    form.ProcessArguments(args);
                    form.Activate();
                }
            }

    Et form.ProcessArguments se charge de traiter les arguments passés par la nouvelle instance à l'instance déjà existante ...

    (Et c'est ce que fait normalement le lien que j'ai posté plus haut)

  6. #6
    AP
    AP est déconnecté
    Membre chevronné
    Avatar de AP
    Profil pro
    Inscrit en
    Avril 2002
    Messages
    480
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France, Rhône (Rhône Alpes)

    Informations forums :
    Inscription : Avril 2002
    Messages : 480
    Par défaut
    Heu la solution est toute simple, c'est une case à cocher dans les propriétés du projet http://www.codeproject.com/KB/vb/vb2005ga.aspx

  7. #7
    Expert confirmé
    Avatar de smyley
    Profil pro
    Inscrit en
    Juin 2003
    Messages
    6 270
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2003
    Messages : 6 270
    Par défaut
    Citation Envoyé par AP Voir le message
    Heu la solution est toute simple, c'est une case à cocher dans les propriétés du projet http://www.codeproject.com/KB/vb/vb2005ga.aspx
    Le travail est vraiment mâché en vb.net

  8. #8
    Membre éprouvé

    Homme Profil pro
    kiné passionné de dev
    Inscrit en
    Mars 2006
    Messages
    1 570
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France

    Informations professionnelles :
    Activité : kiné passionné de dev

    Informations forums :
    Inscription : Mars 2006
    Messages : 1 570
    Billets dans le blog
    1
    Par défaut
    Citation Envoyé par AP Voir le message
    Heu la solution est toute simple, c'est une case à cocher dans les propriétés du projet http://www.codeproject.com/KB/vb/vb2005ga.aspx
    Oui, mais pas si on utilise Sub Main
    Sinon, pour Smyley, c'est vrai que je pourrais tout mettre en code, mais il y a une solution simple avec le framework, je voulais donc l'utiliser.
    Si ce n'est pas possible, je vais devoir faire comme ça.

Discussions similaires

  1. [VB6][SQL] Ouvrir mon application avec 2 profils différents
    Par angus9 dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 24/12/2010, 16h21
  2. Réponses: 7
    Dernier message: 22/08/2007, 12h19
  3. [WinForms]ouvrir mon application depuis un fichier
    Par jul54 dans le forum Général Dotnet
    Réponses: 8
    Dernier message: 22/09/2006, 14h35
  4. Comment ouvrir mon application aux autres?
    Par korntex5 dans le forum Langage
    Réponses: 2
    Dernier message: 27/04/2006, 15h25
  5. ouvrir mon application hors environnement access
    Par azde7015 dans le forum Access
    Réponses: 1
    Dernier message: 15/02/2006, 08h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo