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

C# Discussion :

Lancement application desktop sur une autre session utilisateur depuis un service


Sujet :

C#

  1. #1
    Membre éclairé Avatar de -N4w4k-
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2011
    Messages
    545
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Novembre 2011
    Messages : 545
    Points : 801
    Points
    801
    Par défaut Lancement application desktop sur une autre session utilisateur depuis un service
    Bonjour,

    Depuis un service sous le compte LocalSystem, j'ai besoin de lancer un programme desktop (avec fenêtre) ((car c'est un programme COM, et qui s'inscrit dans la ROT après l'affichage de ses fenêtres)). Pas de mode silencieux disponible.

    La seule option que j'ai trouvé serait de le lancer dans une session d'un utilisateur.

    Mais comment ?

    J'ai pour le moment essayé beaucoup de choses, autour de CreateProcessAsUser, avec/sans ouverture d'une station windows "Winsta0\default", sans grand succès.
    Je pense que mon souci vient du fait que je n'ai pas de sessionId pour ouvrir le process (l'utilisateur n'étant pas connecté au serveur). En étant connecté à la main, avec ce sessionId, il y a un mieux (un message d'erreur apparaît \o/), mais le process ne se lance donc pas correctement.

    Voici le dernier code que j'ai essayé:
    Code : 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
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.InteropServices.ComTypes;
    using System.Runtime.InteropServices;
     
    using System.Security.Principal;
    using System.Security.Permissions;
    using Microsoft.Win32.SafeHandles;
    using System.Runtime.ConstrainedExecution;
    using System.Security;
     
    namespace ConsoleApplication1
    {
        public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            private SafeTokenHandle()
                : base(true)
            {
            }
     
            [DllImport("kernel32.dll")]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            [SuppressUnmanagedCodeSecurity]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool CloseHandle(IntPtr handle);
     
            protected override bool ReleaseHandle()
            {
                return CloseHandle(handle);
            }
        }
        public sealed class SafeWindowStationHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeWindowStationHandle()
                : base(true)
            {
            }
     
            protected override bool ReleaseHandle()
            {
                return ProcessUtility.CloseWindowStation(handle);
            }
        }
     
        public class ProcessUtility
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct STARTUPINFO
            {
                public Int32 cb;
                public string lpReserved;
                public string lpDesktop;
                public string lpTitle;
                public Int32 dwX;
                public Int32 dwY;
                public Int32 dwXSize;
                public Int32 dwXCountChars;
                public Int32 dwYCountChars;
                public Int32 dwFillAttribute;
                public Int32 dwFlags;
                public Int16 wShowWindow;
                public Int16 cbReserved2;
                public IntPtr lpReserved2;
                public IntPtr hStdInput;
                public IntPtr hStdOutput;
                public IntPtr hStdError;
            }
     
            [StructLayout(LayoutKind.Sequential)]
            public struct PROCESS_INFORMATION
            {
                public IntPtr hProcess;
                public IntPtr hThread;
                public Int32 dwProcessID;
                public Int32 dwThreadID;
            }
     
            [StructLayout(LayoutKind.Sequential)]
            public struct SECURITY_ATTRIBUTES
            {
                public Int32 Length;
                public IntPtr lpSecurityDescriptor;
                public bool bInheritHandle;
            }
     
            public enum SECURITY_IMPERSONATION_LEVEL
            {
                SecurityAnonymous,
                SecurityIdentification,
                SecurityImpersonation,
                SecurityDelegation
            }
     
            public enum TOKEN_TYPE
            {
                TokenPrimary = 1,
                TokenImpersonation
            }
     
            public const int GENERIC_ALL_ACCESS = 0x10000000;
            //public const int GENERIC_ALL_ACCESS = 0xf01ff;
     
            [
               DllImport("kernel32.dll",
                  EntryPoint = "CloseHandle", SetLastError = true,
                  CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)
            ]
            public static extern bool CloseHandle(IntPtr handle);
     
            [
               DllImport("advapi32.dll",
                  EntryPoint = "CreateProcessAsUser", SetLastError = true,
                  CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)
            ]
            public static extern bool
               CreateProcessAsUser(IntPtr hToken, string lpApplicationName, string lpCommandLine,
                                   ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes,
                                   bool bInheritHandle, Int32 dwCreationFlags, IntPtr lpEnvrionment,
                                   string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo,
                                   ref PROCESS_INFORMATION lpProcessInformation);
     
            [
               DllImport("advapi32.dll",
                  EntryPoint = "DuplicateTokenEx")
            ]
            public static extern bool
               DuplicateTokenEx(SafeTokenHandle hExistingToken, Int32 dwDesiredAccess,
                                IntPtr lpThreadAttributes,
                                Int32 ImpersonationLevel, Int32 dwTokenType,
                                ref IntPtr phNewToken);
     
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
            public static extern SafeWindowStationHandle OpenWindowStation(
                [MarshalAs(UnmanagedType.LPTStr)]
            string lpszWinSta,
                [MarshalAs(UnmanagedType.Bool)]
            bool fInherit,
                uint dwDesiredAccess
            );
            [return: MarshalAs(UnmanagedType.Bool)]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
            public static extern bool CloseWindowStation(IntPtr hWinsta);
     
            [return: MarshalAs(UnmanagedType.Bool)]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
            public static extern bool CloseWindowStation(SafeWindowStationHandle hWinsta);
     
            [DllImport("user32.dll", SetLastError = true)]
            public static extern bool SetProcessWindowStation(SafeWindowStationHandle hWinSta);
     
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            [DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
            public static extern SafeWindowStationHandle GetProcessWindowStation();
     
            [DllImport("user32.dll")]
            public static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags,
               bool fInherit, uint dwDesiredAccess);
     
            [DllImport("user32.dll", SetLastError = true)]
            public static extern bool CloseDesktop(IntPtr hDesktop);
     
            [DllImport("Kernel32.dll", SetLastError = true)]
            [return: MarshalAs(UnmanagedType.U4)]
            public static extern UInt32 WTSGetActiveConsoleSessionId();
     
            [DllImport("advapi32.dll", SetLastError = true)]
            public static extern Boolean SetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass,
                ref UInt32 TokenInformation, UInt32 TokenInformationLength);
        }
     
        public enum TOKEN_INFORMATION_CLASS
        {
            /// <summary>
            /// The buffer receives a TOKEN_USER structure that contains the user account of the token.
            /// </summary>
            TokenUser = 1,
     
            /// <summary>
            /// The buffer receives a TOKEN_GROUPS structure that contains the group accounts associated with the token.
            /// </summary>
            TokenGroups,
     
            /// <summary>
            /// The buffer receives a TOKEN_PRIVILEGES structure that contains the privileges of the token.
            /// </summary>
            TokenPrivileges,
     
            /// <summary>
            /// The buffer receives a TOKEN_OWNER structure that contains the default owner security identifier (SID) for newly created objects.
            /// </summary>
            TokenOwner,
     
            /// <summary>
            /// The buffer receives a TOKEN_PRIMARY_GROUP structure that contains the default primary group SID for newly created objects.
            /// </summary>
            TokenPrimaryGroup,
     
            /// <summary>
            /// The buffer receives a TOKEN_DEFAULT_DACL structure that contains the default DACL for newly created objects.
            /// </summary>
            TokenDefaultDacl,
     
            /// <summary>
            /// The buffer receives a TOKEN_SOURCE structure that contains the source of the token. TOKEN_QUERY_SOURCE access is needed to retrieve this information.
            /// </summary>
            TokenSource,
     
            /// <summary>
            /// The buffer receives a TOKEN_TYPE value that indicates whether the token is a primary or impersonation token.
            /// </summary>
            TokenType,
     
            /// <summary>
            /// The buffer receives a SECURITY_IMPERSONATION_LEVEL value that indicates the impersonation level of the token. If the access token is not an impersonation token, the function fails.
            /// </summary>
            TokenImpersonationLevel,
     
            /// <summary>
            /// The buffer receives a TOKEN_STATISTICS structure that contains various token statistics.
            /// </summary>
            TokenStatistics,
     
            /// <summary>
            /// The buffer receives a TOKEN_GROUPS structure that contains the list of restricting SIDs in a restricted token.
            /// </summary>
            TokenRestrictedSids,
     
            /// <summary>
            /// The buffer receives a DWORD value that indicates the Terminal Services session identifier that is associated with the token.
            /// </summary>
            TokenSessionId,
     
            /// <summary>
            /// The buffer receives a TOKEN_GROUPS_AND_PRIVILEGES structure that contains the user SID, the group accounts, the restricted SIDs, and the authentication ID associated with the token.
            /// </summary>
            TokenGroupsAndPrivileges,
     
            /// <summary>
            /// Reserved.
            /// </summary>
            TokenSessionReference,
     
            /// <summary>
            /// The buffer receives a DWORD value that is nonzero if the token includes the SANDBOX_INERT flag.
            /// </summary>
            TokenSandBoxInert,
     
            /// <summary>
            /// Reserved.
            /// </summary>
            TokenAuditPolicy,
     
            /// <summary>
            /// The buffer receives a TOKEN_ORIGIN value.
            /// </summary>
            TokenOrigin,
     
            /// <summary>
            /// The buffer receives a TOKEN_ELEVATION_TYPE value that specifies the elevation level of the token.
            /// </summary>
            TokenElevationType,
     
            /// <summary>
            /// The buffer receives a TOKEN_LINKED_TOKEN structure that contains a handle to another token that is linked to this token.
            /// </summary>
            TokenLinkedToken,
     
            /// <summary>
            /// The buffer receives a TOKEN_ELEVATION structure that specifies whether the token is elevated.
            /// </summary>
            TokenElevation,
     
            /// <summary>
            /// The buffer receives a DWORD value that is nonzero if the token has ever been filtered.
            /// </summary>
            TokenHasRestrictions,
     
            /// <summary>
            /// The buffer receives a TOKEN_ACCESS_INFORMATION structure that specifies security information contained in the token.
            /// </summary>
            TokenAccessInformation,
     
            /// <summary>
            /// The buffer receives a DWORD value that is nonzero if virtualization is allowed for the token.
            /// </summary>
            TokenVirtualizationAllowed,
     
            /// <summary>
            /// The buffer receives a DWORD value that is nonzero if virtualization is enabled for the token.
            /// </summary>
            TokenVirtualizationEnabled,
     
            /// <summary>
            /// The buffer receives a TOKEN_MANDATORY_LABEL structure that specifies the token's integrity level.
            /// </summary>
            TokenIntegrityLevel,
     
            /// <summary>
            /// The buffer receives a DWORD value that is nonzero if the token has the UIAccess flag set.
            /// </summary>
            TokenUIAccess,
     
            /// <summary>
            /// The buffer receives a TOKEN_MANDATORY_POLICY structure that specifies the token's mandatory integrity policy.
            /// </summary>
            TokenMandatoryPolicy,
     
            /// <summary>
            /// The buffer receives the token's logon security identifier (SID).
            /// </summary>
            TokenLogonSid,
     
            /// <summary>
            /// The maximum value for this enumeration
            /// </summary>
            MaxTokenInfoClass
        }
     
     
     
     
        class Program
        {
            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
                int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
     
            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            public extern static bool CloseHandle(IntPtr handle);
     
     
            static void Main(string[] args)
            {
                String hein = Console.ReadLine();
                try
                {
                    if (StartE3())
                    {
                        //try
                        {
                            /*
                            e3.e3Application come3 = (e3.e3Application)Activator.CreateInstance(System.Type.GetTypeFromProgID("CT.Application"));
     
                            Console.WriteLine(come3.GetId());
                            
                            e3.e3Job jobe3 = (e3.e3Job)come3.CreateJobObject();
     
                            jobe3.New("TestInterface");
     
                            jobe3.SaveAs(@"D:\concept\webapps\concept2\alstom\autoplan\test_appli.e3s");
     
                            jobe3.Close();
                            */
                        }
                    }
                    else
                    {
                        Console.WriteLine("test2");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error : " + ex.Message);
                }
                finally
                {
                    Console.WriteLine("Whatttttt");
                }
            }
            static bool StartE3pro()
            {
                SafeTokenHandle safeTokenHandle;
     
                const int LOGON32_PROVIDER_DEFAULT = 0;
                //This parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_INTERACTIVE = 2;
     
                // Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser("username", "server", "password",
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                    out safeTokenHandle);
     
                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    //Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                    //Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
     
                    // Use the token handle returned by LogonUser.
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
     
                            // If E3 already running -> Ecad should be launch too
     
                            var le3 = Process.GetProcessesByName("E3.Series");
     
                            if (le3.Length > 0)
                            {
                                Console.WriteLine("E3 running");
                                return false;
                            }
     
                            if (CountE3() > 0)
                            {
                                Console.WriteLine("COM E3 running");
                                return false;
                            }
     
                            IntPtr hToken = WindowsIdentity.GetCurrent().Token;
                            IntPtr hDupedToken = IntPtr.Zero;
     
                            Process pe3 = new Process();
                            pe3.StartInfo.FileName = @"D:\E3.Series\E3.Series.exe";
     
                            pe3.StartInfo.UseShellExecute = false;
                            pe3.StartInfo.RedirectStandardError = false;
                            pe3.StartInfo.RedirectStandardInput = false;
                            pe3.StartInfo.RedirectStandardOutput = false;
     
                            if (!pe3.Start())
                            {
                                Console.WriteLine("E3 could not start");
                                return false;
                            }
     
     
                            int waitcount = 0;
                            while (CountE3() == 0 && waitcount < 30)
                            {
                                // Was it enough for E3 to start ?
                                System.Threading.Thread.Sleep(2000);
                                waitcount++;
                            }
     
                            if (CountE3() == 0)
                            {
                                // Bug lancement
                                //pe3.Kill();
                                Console.WriteLine("E3 launched, but no COM registration in time");
     
                                return false;
                            }
                            else
                            {
                                // Launch EcadAutoProcess
     
                                Process pecad = new Process();
                                pecad.StartInfo.FileName = @"D:\E3.Series\scripts\CbrEcadAutoProcess.exe";
     
                                pecad.StartInfo.UseShellExecute = false;
                                pecad.StartInfo.RedirectStandardError = false;
                                pecad.StartInfo.RedirectStandardInput = false;
                                pecad.StartInfo.RedirectStandardOutput = false;
     
                                if (pecad.Start())
                                {
                                    //Console.WriteLine("AutoPlan started");
                                    return true;
                                }
                                else
                                {
                                    Console.WriteLine("AutoPlan failed");
                                    return false;
                                }
                            }
     
                        }
                    }
                    // Releasing the context object stops the impersonation
                    // Check the identity.
                    //Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                }
     
            }
            static bool StartE3()
            {
                SafeTokenHandle safeTokenHandle;
     
                const int LOGON32_PROVIDER_DEFAULT = 0;
                //This parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_INTERACTIVE = 2;
     
                // Call LogonUser to obtain a handle to an access token.
                bool returnValue = LogonUser("username", "server", "password",
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                    out safeTokenHandle);
     
                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    //Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                    //Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
     
                    // Use the token handle returned by LogonUser.
                    IntPtr hToken;
                    IntPtr hDupedToken = IntPtr.Zero;
                    UInt32 sessionId = 1;
                    //using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        //using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
                            //hToken = WindowsIdentity.GetCurrent().Token;
     
                            bool result2 = ProcessUtility.DuplicateTokenEx(
                                //hToken,
                                  safeTokenHandle,
                                  ProcessUtility.GENERIC_ALL_ACCESS,
                                  IntPtr.Zero,
                                  (int)ProcessUtility.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                                  (int)ProcessUtility.TOKEN_TYPE.TokenPrimary,
                                  ref hDupedToken
                               );
     
                            if (!result2)
                            {
                                Console.WriteLine("DuplicateTokenEx failed");
                                return false;
                            }
     
                            sessionId = 11;// ProcessUtility.WTSGetActiveConsoleSessionId();
     
                            ProcessUtility.SetTokenInformation(hDupedToken, TOKEN_INFORMATION_CLASS.TokenSessionId, ref sessionId, (UInt32)IntPtr.Size);
     
                        }
                    }
     
                    // If E3 already running -> Ecad should be launch too
     
                    var le3 = Process.GetProcessesByName("E3.Series");
     
                    if (le3.Length > 0)
                    {
                        Console.WriteLine("E3 running");
                        return false;
                    }
     
                    if (CountE3() > 0)
                    {
                        Console.WriteLine("COM E3 running");
                        return false;
                    }
     
     
     
     
                    SafeWindowStationHandle hwinstaSave;
                    SafeWindowStationHandle hwinsta;
     
                    if ((hwinstaSave = ProcessUtility.GetProcessWindowStation()) == null)
                    {
                        Console.WriteLine("GetProcessWindowStation failed");
                        return false;
                    }
     
                    hwinsta = ProcessUtility.OpenWindowStation(
                       "winsta0",                   // the interactive window station 
                       false,                       // handle is not inheritable
                       0x20000 | 0x40000);
     
                    if (hwinsta == null)
                    {
                        Console.WriteLine("OpenWindowStation failed");
                        return false;
                    }
     
                    if (!ProcessUtility.SetProcessWindowStation(hwinsta))
                    {
                        Console.WriteLine("SetProcessWindowStation failed");
                        return false;
                    }
     
                    IntPtr hdesk = ProcessUtility.OpenDesktop(
    "default",     // the interactive window station 
    0,             // no interaction with other desktop processes
    false,         // handle is not inheritable
    0x20000 | // request the rights to read and write the DACL
    0x40000 |
    0x80 |
    0x1);
     
                    ProcessUtility.CloseWindowStation(hwinsta);
                    ProcessUtility.CloseDesktop(hdesk);
     
                    ProcessUtility.PROCESS_INFORMATION pi = new ProcessUtility.PROCESS_INFORMATION();
     
                    ProcessUtility.SECURITY_ATTRIBUTES sa = new ProcessUtility.SECURITY_ATTRIBUTES();
                    sa.Length = Marshal.SizeOf(sa);
     
                    bool result;
     
     
                    ProcessUtility.STARTUPINFO si = new ProcessUtility.STARTUPINFO();
                    si.cb = Marshal.SizeOf(si);
                    si.lpDesktop = @"winsta0\default";
     
                    result = ProcessUtility.CreateProcessAsUser(
                                         hDupedToken,
                        //safeTokenHandle,
                                         null,
                                         @"D:\E3.Series\E3.Series.exe",
                                         ref sa, ref sa,
                                         true, 0, IntPtr.Zero,
                                         @"D:\E3.Series", ref si, ref pi
                                   );
     
                    //ProcessUtility.SetProcessWindowStation(hwinstaSave);
     
                    if (!result)
                    {
                        int error = Marshal.GetLastWin32Error();
                        string message = String.Format("CreateProcessAsUser Error: {0}", error);
                        //throw new ApplicationException(message);
     
                        Console.WriteLine("E3 not starting " + message);
                        return false;
     
                    }
     
     
     
                    int waitcount = 0;
                    while (CountE3() == 0 && waitcount < 30)
                    {
                        // Was it enough for E3 to start ?
                        System.Threading.Thread.Sleep(2000);
                        waitcount++;
                    }
     
                    if (CountE3() == 0)
                    {
                        // Bug lancement
                        //pe3.Kill();
                        Console.WriteLine("E3 launched, but no COM registration in time");
     
                        return false;
                    }
                    else
                    {
                        // Launch EcadAutoProcess
     
                        Process pecad = new Process();
                        pecad.StartInfo.FileName = @"D:\E3.Series\scripts\CbrEcadAutoProcess.exe";
     
                        pecad.StartInfo.UseShellExecute = false;
                        pecad.StartInfo.RedirectStandardError = false;
                        pecad.StartInfo.RedirectStandardInput = false;
                        pecad.StartInfo.RedirectStandardOutput = false;
     
                        if (pecad.Start())
                        {
                            //Console.WriteLine("AutoPlan started");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine("AutoPlan failed");
                            return false;
                        }
                    }
     
     
                    // Releasing the context object stops the impersonation
                    // Check the identity.
                    //Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                }
     
            }
     
            [DllImport("ole32.dll")]
            public static extern int GetRunningObjectTable(uint reserved, out IRunningObjectTable pprot);
            [DllImport("ole32.dll")]
            public static extern int CreateBindCtx(uint reserved, out IBindCtx bindCtx);
     
            public static int CountE3()
            {
                int retour = 0;
                IRunningObjectTable rot;
                if (GetRunningObjectTable(0, out rot) == 0)
                {
                    IEnumMoniker emok;
                    rot.EnumRunning(out emok);
     
                    IMoniker[] moks = new IMoniker[1];
                    IntPtr ipmoks = IntPtr.Zero;
     
                    IBindCtx ctx;
                    CreateBindCtx(0, out ctx);
     
                    List<IMoniker> _e3 = new List<IMoniker>();
                    while (emok.Next(1, moks, ipmoks) == 0)
                    {
                        string dname;
                        moks[0].GetDisplayName(ctx, null, out dname);
     
                        if (dname.StartsWith("!E3Application"))
                        {
                            ++retour;
                        }
                    }
                }
     
                return retour;
            }
        }
    }

    Je suis à la recherche de toute piste pour pouvoir y arriver, même à faire totalement autrement..

    Merci d'avance
    J’ai des questions à toutes vos réponses!

  2. #2
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    question qui revient souvent

    faire un programme windows forms (par exemple) qui se lance à l'ouverture de session (visible dans le system tray ou pas) qui dialogue avec le service (cannaux nommés, tcp ...)
    le service donne alors l'ordre à ce programme de lancer l'autre programme

    après il faut savoir qu'à un instant T windows peut avoir plusieurs sessions d'ouvertes
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  3. #3
    Membre régulier
    Inscrit en
    Octobre 2005
    Messages
    62
    Détails du profil
    Informations forums :
    Inscription : Octobre 2005
    Messages : 62
    Points : 85
    Points
    85
    Par défaut
    Citation Envoyé par Pol63 Voir le message
    question qui revient souvent

    faire un programme windows forms (par exemple) qui se lance à l'ouverture de session (visible dans le system tray ou pas) qui dialogue avec le service (cannaux nommés, tcp ...)
    le service donne alors l'ordre à ce programme de lancer l'autre programme

    après il faut savoir qu'à un instant T windows peut avoir plusieurs sessions d'ouvertes
    Il n'y a aucune ouverture de session, aucun utilisateur ne se loggue à aucun moment.
    Tout doit être fait depuis le service, ou depuis le compte Local System.

    L'essai avec un user loggué était un essai, non reproduisible en production.

  4. #4
    Membre éclairé Avatar de -N4w4k-
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2011
    Messages
    545
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Novembre 2011
    Messages : 545
    Points : 801
    Points
    801
    Par défaut
    Salut Pol63,

    Spazou a répondu à ma place, on est ensemble sur le projet!
    J’ai des questions à toutes vos réponses!

  5. #5
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    tu veux lancer un programme dans une session mais tu n'as pas de session ?
    je pense qu'il n'y a pas plus à discuter alors

    si c'est pour un bricolage d'une fois, y a peut etre la case à cocher "interragir avec le bureau"
    si c'est pour du durable sur plusieurs serveurs, que fais ton truc COM ? tu peux pas le redévelopper ?
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  6. #6
    Membre éclairé Avatar de -N4w4k-
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2011
    Messages
    545
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Novembre 2011
    Messages : 545
    Points : 801
    Points
    801
    Par défaut
    Ce qu'on a essayé de faire pour le moment c'est justement d'ouvrir une session utilisateur qui a un bureau pour y lancer le programme, mais jusqu'à maintenant on a seulement réussi à voir le programme se lancer sous la dite session avant de crasher.. Ce qui nous donne l'impression d'être vraiment proche du but!

    C'est censé être une fonctionnalité durable, et le programme à lancer est incontournable!
    J’ai des questions à toutes vos réponses!

  7. #7
    Membre régulier
    Inscrit en
    Octobre 2005
    Messages
    62
    Détails du profil
    Informations forums :
    Inscription : Octobre 2005
    Messages : 62
    Points : 85
    Points
    85
    Par défaut
    Citation Envoyé par Pol63 Voir le message
    tu veux lancer un programme dans une session mais tu n'as pas de session ?
    je pense qu'il n'y a pas plus à discuter alors

    si c'est pour un bricolage d'une fois, y a peut etre la case à cocher "interragir avec le bureau"
    si c'est pour du durable sur plusieurs serveurs, que fais ton truc COM ? tu peux pas le redévelopper ?
    Il n'y a pas de session ouverte oui, mais si il est possible d'en ouvrir une depuis un service, les identifiants/mot de passe utilisateur sont connu et utilisable.

    "Interagir avec le bureau" ne fonctionne pas pour cette appli, déjà testé avec Word/Excel, les applis COM ne répondent pas correctement.

    C'est un programme tiers spécialisé, pas reprogrammable :/

  8. #8
    Expert éminent sénior Avatar de Pol63
    Homme Profil pro
    .NET / SQL SERVER
    Inscrit en
    Avril 2007
    Messages
    14 154
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Puy de Dôme (Auvergne)

    Informations professionnelles :
    Activité : .NET / SQL SERVER

    Informations forums :
    Inscription : Avril 2007
    Messages : 14 154
    Points : 25 072
    Points
    25 072
    Par défaut
    y a un système qui permet l'ouverture automatique d'une session au démarrage si ca peut vous aider
    http://www.octetmalin.net/windows/tu...-mot-passe.php
    (et là mon idée irait, le processus étant lancé depuis un processus qui est déjà hébergé par la session)
    (quitte à verrouiller la session dans la foulée par code, enfin déjà tester si ca marche avant de tenter le lock)
    Cours complets, tutos et autres FAQ ici : C# - VB.NET

  9. #9
    Membre éclairé Avatar de -N4w4k-
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Novembre 2011
    Messages
    545
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Industrie

    Informations forums :
    Inscription : Novembre 2011
    Messages : 545
    Points : 801
    Points
    801
    Par défaut
    Ton idée aurait été bien mais on ne peut pas se permettre d'ouvrir une session utilisateur au démarrage
    J’ai des questions à toutes vos réponses!

Discussions similaires

  1. Déploiement d'une application java sur une autre machine
    Par enneite2 dans le forum Débuter avec Java
    Réponses: 4
    Dernier message: 16/05/2011, 12h51
  2. Erreur lors du lancement d'Eclipse sur une autre JVM
    Par mesken dans le forum Eclipse
    Réponses: 2
    Dernier message: 26/03/2011, 11h53
  3. Réponses: 3
    Dernier message: 25/10/2007, 11h47
  4. [Sécurité] 2 utilisateurs sur une même session
    Par Sandara dans le forum Langage
    Réponses: 3
    Dernier message: 19/03/2007, 09h29
  5. POPUP: Rediriger l'utilisateur sur une autre page
    Par anutka dans le forum Général JavaScript
    Réponses: 11
    Dernier message: 20/09/2005, 11h36

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