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 :

Parser du c# en c#


Sujet :

C#

  1. #1
    Nouveau membre du Club Avatar de M.Leroy
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2019
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2019
    Messages : 49
    Points : 31
    Points
    31
    Par défaut Parser du c# en c#
    Bonjour,

    Je souhaiterais parser du code c# , plus précisément le code généré par CodeDomDesignerLoader en bref le concepteur de fenêtre mais sous cette forme là :
    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
     
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------
     
    namespace DesignerHostSample
    {
        using System;
        using System.ComponentModel;
        using System.Windows.Forms;
     
     
        public class Form1 : System.Windows.Forms.Form
        {
     
            private System.Windows.Forms.Button button1;
     
            private System.Windows.Forms.TextBox textBox1;
     
            private System.Windows.Forms.CheckBox checkBox1;
     
            private System.Windows.Forms.Button button2;
     
            public Form1()
            {
                this.InitializeComponent();
            }
     
            [System.STAThreadAttribute()]
            public static void Main()
            {
                System.Windows.Forms.Application.Run(new Form1());
            }
     
            private void InitializeComponent()
            {
                this.button1 = new System.Windows.Forms.Button();
                this.textBox1 = new System.Windows.Forms.TextBox();
                this.checkBox1 = new System.Windows.Forms.CheckBox();
                this.button2 = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // button1
                // 
                this.button1.Location = new System.Drawing.Point(237, 44);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(75, 23);
                this.button1.TabIndex = 0;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
                // 
                // textBox1
                // 
                this.textBox1.Location = new System.Drawing.Point(78, 105);
                this.textBox1.Name = "textBox1";
                this.textBox1.Size = new System.Drawing.Size(100, 20);
                this.textBox1.TabIndex = 1;
                // 
                // checkBox1
                // 
                this.checkBox1.Location = new System.Drawing.Point(27, 77);
                this.checkBox1.Name = "checkBox1";
                this.checkBox1.Size = new System.Drawing.Size(104, 24);
                this.checkBox1.TabIndex = 2;
                this.checkBox1.Text = "checkBox1";
                this.checkBox1.UseVisualStyleBackColor = true;
                // 
                // button2
                // 
                this.button2.Location = new System.Drawing.Point(186, 15);
                this.button2.Name = "button2";
                this.button2.Size = new System.Drawing.Size(75, 23);
                this.button2.TabIndex = 3;
                this.button2.Text = "button2";
                this.button2.UseVisualStyleBackColor = true;
                // 
                // Form1
                // 
                this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
                this.ClientSize = new System.Drawing.Size(456, 261);
                this.Controls.Add(this.button2);
                this.Controls.Add(this.checkBox1);
                this.Controls.Add(this.textBox1);
                this.Controls.Add(this.button1);
                this.Name = "Form1";
                this.ResumeLayout(false);
                this.PerformLayout();
            }
        }
    }
    dans le but de le convertir dans "mon" propre langage de programmation :
    Nom : cpcdosc.PNG
Affichages : 190
Taille : 13,2 Ko
    etc...
    Je vous remercie

  2. #2
    Membre habitué
    Profil pro
    Inscrit en
    Décembre 2006
    Messages
    412
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Décembre 2006
    Messages : 412
    Points : 149
    Points
    149
    Par défaut
    Bonjours,

    tu veux faire quoi présentement, interpréter et exécuter ton "language"

    ou juste en faire un fichier de configuration pour recharger les préférences ?

  3. #3
    Nouveau membre du Club Avatar de M.Leroy
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2019
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2019
    Messages : 49
    Points : 31
    Points
    31
    Par défaut
    Citation Envoyé par panthere noire Voir le message
    Bonjours,

    tu veux faire quoi présentement, interpréter et exécuter ton "language"

    ou juste en faire un fichier de configuration pour recharger les préférences ?

    Je veux juste faire un travail de traduction, le concepteur de fenêtre génère du code c# et je veux traduire ce code dans le langage de la capture d'écran juste dans le but de le traduire. Il sera interprété plus tard par un OS différent de Windows.
    merci

    voici le code qui permet de créer le code c# avec le concepteur de fenêtre en utilisant la sérialisation
    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
     
    using System;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.ComponentModel.Design.Serialization;
    using System.Collections;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Reflection;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text;
    using System.Windows.Forms;
    using System.CodeDom.Compiler;
    using System.CodeDom;
    using Microsoft.CSharp;
    using Microsoft.VisualBasic;
     
    namespace Loader
    {
    	/// <summary>
    	/// This is used by the CodeDomHostLoader to generate the CodeCompleUnit
    	/// </summary>
    	internal class CodeGen 
    	{
    		private CodeCompileUnit codeCompileUnit;
    		private CodeNamespace ns;
    		private CodeTypeDeclaration myDesignerClass = new CodeTypeDeclaration();
    		private CodeMemberMethod initializeComponent = new CodeMemberMethod();
    		private IDesignerHost host;
    		private IComponent root;
     
    		private static readonly Attribute[] propertyAttributes = new Attribute[] 
    		{
    			DesignOnlyAttribute.No
    		};
     
            /// <summary>
            /// This function generates the default CodeCompileUnit template
            /// </summary>
            public CodeCompileUnit GetCodeCompileUnit(IDesignerHost host)
    		{
                this.host = host;
                IDesignerHost idh = (IDesignerHost)this.host.GetService(typeof(IDesignerHost));
                root = idh.RootComponent;
                Hashtable nametable = new Hashtable(idh.Container.Components.Count);
     
                ns = new CodeNamespace("DesignerHostSample");
                myDesignerClass = new CodeTypeDeclaration();
                initializeComponent = new CodeMemberMethod();
     
                CodeCompileUnit code = new CodeCompileUnit();
     
                // Imports
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
                ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
                code.Namespaces.Add(ns);
                myDesignerClass = new CodeTypeDeclaration(root.Site.Name);
                myDesignerClass.BaseTypes.Add(typeof(Form).FullName);
     
                IDesignerSerializationManager manager = host.GetService(typeof(IDesignerSerializationManager)) as IDesignerSerializationManager;
     
                ns.Types.Add(myDesignerClass);
     
                // Constructor
                CodeConstructor con = new CodeConstructor();
     
                con.Attributes = MemberAttributes.Public;
                con.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "InitializeComponent")));
                myDesignerClass.Members.Add(con);
     
                // Main
                CodeEntryPointMethod main = new CodeEntryPointMethod();
     
                main.Name = "Main";
                main.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                main.CustomAttributes.Add(new CodeAttributeDeclaration("System.STAThreadAttribute"));
                main.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Windows.Forms.Application)), "Run"), new CodeExpression[] {
    				new CodeObjectCreateExpression(new CodeTypeReference(root.Site.Name))
    			}));
                myDesignerClass.Members.Add(main);
     
                // InitializeComponent
                initializeComponent.Name = "InitializeComponent";
                initializeComponent.Attributes = MemberAttributes.Private;
                initializeComponent.ReturnType = new CodeTypeReference(typeof(void));
                myDesignerClass.Members.Add(initializeComponent);
                codeCompileUnit = code;
                return codeCompileUnit;
    		}
     
    	}// class
    } // namespace

  4. #4
    Nouveau membre du Club Avatar de M.Leroy
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2019
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2019
    Messages : 49
    Points : 31
    Points
    31
    Par défaut
    Avec une sérialisation en Xml on ne peut pas copier,coller...
    Et avec C# on ne peut pas enregistrer la fenêtre.. Ils me font rire chez Microsoft
    designer.rar
    http://www.windows-tech.info/3/eb67e8dd83693a79.php
    peut être que la solution se trouve dans l'ouverture d'une assembly comme écrit sur cette page à la fin..
    il y a aussi la source de softwarezator qui est intéressante
    https://github.com/veler/SoftwareZator-2012
    Ou rester sur du XML (ou mon parser fonctionne déjà) en essayant d'implémenter les fonctions copier...coller Néanmoins supprimer et centrer sur le formulaire fonctionnent.
    comme ici https://www.codeproject.com/articles...-back-together
    Ou bien créer une extension sur Visual Studio qui permet de convertir le code c# généré mais là c'est encore autre chose..

  5. #5
    Membre habitué
    Profil pro
    Inscrit en
    Décembre 2006
    Messages
    412
    Détails du profil
    Informations personnelles :
    Localisation : Suisse

    Informations forums :
    Inscription : Décembre 2006
    Messages : 412
    Points : 149
    Points
    149
    Par défaut
    Dison que c'est pas dans leur intérêt. non seulement coter finance, mai aussi coter ressource...

    Pour ton problème cela dépasse mes compétences je suis débutant en C#... je passe donc la main a quelqu'un d'autre.

  6. #6
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    Citation Envoyé par M.Leroy Voir le message
    Et avec C# on ne peut pas enregistrer la fenêtre.. Ils me font rire chez Microsoft
    Que veux-tu dire "avec c#" ? si c'est le loader CodeDomHostLoader.
    Alors là si de chez Microsoft ils te font rire "jaune" ,moi je me permets à mon tour de rire à tes depens.
    Le code .cs ou .vb genere par le Designer et affiché dans le RichTextBox peut etre sauvegardé à chaque modif en ModeDesign instantanement.

    Il suffit de "trapper" l'event TextChanged du RTB .
    L'exemple de code fourni necessite d'ajouter un handler dans le form MainShell dans le method SwitchToCode:
    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
     
      private void SwitchToCode(string context)
            {
                if (CurrentActiveDocumentLoaderType == LoaderType.NoLoader)
                {
                    MessageBox.Show("Code view is not supported for document loaded without Loaders");
                    return;
                }
     
                if (context == Strings.Xml && CurrentActiveDocumentLoaderType != LoaderType.BasicDesignerLoader)
                {
                    MessageBox.Show("Xml code view is supported only for BasicDesignerLoader");
                    return;
                }
     
                if ((context == Strings.CS || context == Strings.VB || context == Strings.JS) && CurrentActiveDocumentLoaderType != LoaderType.CodeDomDesignerLoader)
                {
                    MessageBox.Show(context + " code view is supported only for CodeDomDesignerLoader");
                    return;
                }
     
                HostControl currentHostControl = CurrentDocumentsHostControl;
     
     
                RichTextBox codeEditor = CurrentDocumentsCodeEditor;
                // -----------------MODIF  PAR  ICI AVEC CE HANDLER
                codeEditor.TextChanged += new EventHandler(codeEditor_TextChanged);
                // -----------------FIN MODIF  
                if (CurrentActiveDocumentLoaderType == LoaderType.BasicDesignerLoader)
                    codeEditor.Text = ((BasicHostLoader)currentHostControl.HostSurface.Loader).GetCode();
                else if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader)
                    codeEditor.Text = ((CodeDomHostLoader)currentHostControl.HostSurface.Loader).GetCode(context);
     
                int index = CurrentDocumentsCodeIndex;
     
                if (this.tabControl1.SelectedIndex != index)
                {
                    _prevIndex = this.tabControl1.SelectedIndex;
                    this.tabControl1.SelectedIndex = index;
                    _curIndex = index;
                }
            }
            // -----------------LE HANDLER DU RTB
            void codeEditor_TextChanged(object sender, EventArgs e)
            {
                RichTextBox rtb =sender as RichTextBox ;
     
                string cleanup = rtb.Text; // obtient la version texte du RTB
                string fileName = Path.Combine(Application.StartupPath, "RTB.txt"); 
                StreamWriter file = new StreamWriter(fileName);
     
                file.Write(cleanup);
                file.Close();
            }
    Le fichier est enregistre dans le répertoire \bin\debug du projet Shell.

    Quant à parser le code c# généré il n' y a que le compilateur C# qui sait le faire .
    Ou un nouveau compilateur du CSharp de ton cru pour le faire.
    Parser veut dire vérifier la conformité de la syntaxe au langage C# ,en plus de nécessiter un "Scanner" dit Analyseur Lexical & un CodeGenerator dit Generateur de code cible (ton language cpc).
    C'est en bref l'écriture d'un compilateur (Parser +Scanner +CodeGenerator)qui n'est pas pas une tache triviale, je tiens à le répéter .
    Ce lien Microsoft (article de MSDN Magazine de February 2008) donne une idée de l'écriture d'un tel compilateur pour le C# & .....en C# !!!.

    https://docs.microsoft.com/en-us/arc...k-using-csharp

    le lien du code d'exemple de cet article n'est plus disponible sur le lien donné .
    Mais on peut le retrouver pour le mois donné (fevrier 2008) sur le site d'archive web suivant (pour les articles MSDN Magazine):

    https://web.archive.org/web/20080922.../cc188707.aspx

    bon code...

  7. #7
    Membre expérimenté
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2007
    Messages
    871
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : Canada

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2007
    Messages : 871
    Points : 1 498
    Points
    1 498
    Par défaut
    Pour le cote purement technique : Roslyn est les compilo de c#, est open source ect, suffisais de chercher: https://github.com/dotnet/roslyn .
    Codedom est deprecie depuis longtemps et est une veritable plaie a utiliser.

    Ensuite, si tu veux 'traduire' du code c# vers autre chose, a toi de l'ecrire, bon courage.

  8. #8
    Membre actif
    Profil pro
    Inscrit en
    Février 2009
    Messages
    155
    Détails du profil
    Informations personnelles :
    Localisation : France, Indre et Loire (Centre)

    Informations forums :
    Inscription : Février 2009
    Messages : 155
    Points : 231
    Points
    231
    Par défaut
    Je ne sais pas dans quel contexte l'appli doit être utilisée ni l'étendue et le type des données à récupérer mais il serait peut-être plus simple d'écrire du code qui récolterait les infos souhaitées et les écrirait dans un fichier.
    Par exemple j'ai rapidement pu sortir ce texte dans l'esprit de ce que tu souhaites (tout ça étant évidemment à affiner) depuis un formulaire :

    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
    Window/	Form1
    .SX	= "816"
    .SY	= "489"
    .Opacite	= "1"
    .BackColor	= "Color [Control]"
    Create/	985768
    End/ Window
     
    System.Windows.Forms.TextBox/	textBox1
    .PX	= "130"
    .PY	= "216"
    .SX	= "166"
    .SY	= "23"
    .text	= "Un peu de texte"
    End/ System.Windows.Forms.TextBox
     
    System.Windows.Forms.Label/	label1
    .PX	= "572"
    .PY	= "256"
    .SX	= "53"
    .SY	= "15"
    .text	= "labelText"
    End/ System.Windows.Forms.Label
     
    System.Windows.Forms.Button/	button1
    .PX	= "510"
    .PY	= "136"
    .SX	= "96"
    .SY	= "41"
    .text	= "button1"
    End/ System.Windows.Forms.Button
     
    System.Windows.Forms.CheckBox/	checkBox1
    .PX	= "326"
    .PY	= "45"
    .SX	= "83"
    .SY	= "19"
    .text	= "checkBox1"
    End/ System.Windows.Forms.CheckBox
    depuis ce code sur l'événement Load :

    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
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;
     
     
    namespace WinFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
     
            private void Form1_Load(object sender, EventArgs e)
            {
                var fileStream = File.Create("c:\\tempo\\structure.txt");
     
                using (StreamWriter sw = new StreamWriter(fileStream))
                {
                    string prop = "";
                    prop = this.Name;
                    sw.WriteLine("Window/\t" + prop);
     
                    prop = this.Width.ToString();
                    sw.WriteLine(".SX\t= \"" + prop + "\"");
     
                    prop = this.Height.ToString();
                    sw.WriteLine(".SY\t= \"" + prop + "\"");
     
                    prop = this.Opacity.ToString();
                    sw.WriteLine(".Opacite\t= \"" + prop + "\"");
     
                    prop = this.BackColor.ToString();
                    sw.WriteLine(".BackColor\t= \"" + prop + "\"");
     
                    prop = this.Handle.ToString();
                    sw.WriteLine("Create/\t" + prop);
     
                    sw.WriteLine("End/ Window");
                    sw.WriteLine();
     
     
                    String cName = "";
                    String cType = "";
                    foreach (Control c in this.Controls)
                    {
                        cType = c.GetType().ToString();
                        cName = c.Name;
                        sw.WriteLine(cType + "/\t" + cName);
     
                        prop = c.Location.X.ToString();
                        sw.WriteLine(".PX\t= \"" + prop + "\"");
     
                        prop = c.Location.Y.ToString();
                        sw.WriteLine(".PY\t= \"" + prop + "\"");
     
                        prop = c.Width.ToString();
                        sw.WriteLine(".SX\t= \"" + prop + "\"");
     
                        prop = c.Height.ToString();
                        sw.WriteLine(".SY\t= \"" + prop + "\"");
     
                        prop = c.Text.ToString();
                        sw.WriteLine(".text\t= \"" + prop + "\"");
     
                        sw.WriteLine("End/ " + cType);
                        sw.WriteLine();
                    }
     
                    sw.Flush();
                    sw.Close();
                }
            }
        }
    }

    Sinon il reste la possibilité de transformer le fichier produit par CodeDomDesignerLoader à l'aide d'un script Perl ou Omnimark, mais c'est affaire de spécialiste.

  9. #9
    Nouveau membre du Club Avatar de M.Leroy
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2019
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Février 2019
    Messages : 49
    Points : 31
    Points
    31
    Par défaut
    Merci pour vos réponses qui sont à étudier sérieusement.
    Néanmoins, ce qui m'incite à passer du Xml (BasicDesignerLoader) au C# (CodeDom..) était seulement le fait que les commandes copier/coller , undo/redo ne fonctionnent pas avec BasicDesignerLoader (---> XML) . J'ai essayé d'implémenter Imenucommandservice (peut-être mal fait) et UndoEngine mais sans succès. Si vous y arrivez dîtes moi.
    Merci

  10. #10
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour ,Mister the King.
    Apres avoir examiné plus en profondeur les soucis soulevés par ton post (n'ayant pas eu assez temps la derniere fois) :
    1/ avec C# ( CodeDomHostLoader) tu peux sauvegarder toutes tes fenetres en mode "conception" tel que dit dans l'article MSDN Magazine.
    Sous forme d'executable rechargeable à volonté (à satieté j'allais dire !).
    Cela est expressement mentionné dans l'article en question car le designer travaille avec une copie en memoire de l' Assembly de Runtime du Designer.

    2/ transpiler le code "run-time" en un fichier texte Cpc.
    Là, tu dois faire une "moulinette" (dont code ci-après) semblable à celle déjà communiquée antérieurement pour le xml mais cette fois plus simple pour CodeDom. Il suffit de "trapper" (attraper en vol) une instance du Form Actif en mode Design et de l'"intropecter" (System.Reflection) via ses PropertiesInfos pour générer ton fichier .txt CPC.

    En bonus ton voeu de Copier/Coller sera exaucé.

    La modif à faire impacte uniquement le Form de lancement MainShell.

    code revu & modifié suivant utilise :
    - une variable currentFrm (pointe sur le fom courant en mode design)
    - une variable sbCpc un stringbuilder qui sert de magasin de stockage de la translation vers CPC
    - un menuitem dit CPCmenuItem à rajouter comme sous menu du menu View (en dessous du sous-menu Code).
    Ce menuItem se charge de récupérer le HostSurface qui permet d'accéder à une instance de IDesignerHost puis à son RootComponent


    code .behind.cs du form dit MainShell revu:

    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
     
    using System;
    using System.Drawing;
    using System.Drawing.Design;
    using System.Collections;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.ComponentModel.Design.Serialization;
    using System.Windows.Forms;
    using System.Data;
    using System.IO;
    using Host;
    using Loader;
    using ToolWindows;
     
    /** MODIF  AJOUT REFERENCES  */
    using System.Reflection;
    using System.Text;
     
    namespace Shell
    {
        /// <summary>
        /// This is the Shell that has the Toolbox, PropertyGrid, hosts Designers, etc.
        /// </summary>
        public partial class MainShell : Form
        {
            private int _formCount = 0;
            private int _userControlCount = 0;
            private int _componentCount = 0;
            private int _grapherCount = 0;
            private HostSurfaceManager _hostSurfaceManager = null;
            private int _prevIndex = 0;
            private int _curIndex = 0;
            /** MODIF .trap du form courant **/
            private Form currentFrm = null;
            /** MODIF .un stringbuilder pour recuperer le fichier texte CPC **/
            private StringBuilder sbCpc = null;
            public MainShell()
            {
                InitializeComponent();
                CustomInitialize();
            }
     
            /// <summary>
            /// Adds custom services to the HostManager like TGoolbox, PropertyGrid, 
            /// SolutionExplorer.
            /// OutputWindow is added as a service. It is used by the HostSurfaceManager
            /// to write out to the OutputWindow. You can add any services
            /// you want.
            /// </summary>
            private void CustomInitialize()
            {
                _hostSurfaceManager = new HostSurfaceManager();
     
                _hostSurfaceManager.AddService(typeof(IToolboxService), this.toolbox1);
                _hostSurfaceManager.AddService(typeof(ToolWindows.SolutionExplorer), this.solutionExplorer1);
                _hostSurfaceManager.AddService(typeof(ToolWindows.OutputWindow), this.OutputWindow);
                _hostSurfaceManager.AddService(typeof(System.Windows.Forms.PropertyGrid), this.propertyGrid1);
     
                codeDomDesignerLoaderMenuItem_Click(null, null);
                this.tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);
                this.noLoaderMenuItem_Click(null, null);
            }
     
            private int CurrentDocumentsDesignIndex
            {
                get
                {
                    string codeText;
                    string designText;
                    int index = 0;
     
                    if (CurrentDocumentView == Strings.Design)
                        return this.tabControl1.SelectedIndex;
                    else
                    {
                        // This is the Code View. So let us find the Design View
                        codeText = this.tabControl1.TabPages[this.tabControl1.SelectedIndex].Text.Trim();
                        designText = codeText.Replace(Strings.Code, Strings.Design);
                        foreach (TabPage tab in this.tabControl1.TabPages)
                        {
                            if (tab.Text == designText)
                                return index;
                            index++;
                        }
                    }
     
                    return -1;
                }
            }
            private int CurrentDocumentsCodeIndex
            {
                get
                {
                    if (CurrentDocumentView == Strings.Code)
                        return this.tabControl1.SelectedIndex;
     
                    int index = 0;
     
                    //HostControl currentHostControl = CurrentDocumentsHostControl;
                    // Find out if the Code Tab already exists
                    string designText = this.tabControl1.TabPages[this.tabControl1.SelectedIndex].Text.Trim();
                    string codeText = designText.Replace(Strings.Design, Strings.Code);
     
                    foreach (TabPage tab in this.tabControl1.TabPages)
                    {
                        if (tab.Text == codeText)
                            return index;
     
                        index++;
                    }
     
                    TabPage tabPage = new TabPage();
     
                    tabPage.Text = codeText;
                    tabPage.Tag = CurrentActiveDocumentLoaderType;
                    this.tabControl1.Controls.Add(tabPage);
     
                    // Create new RichTextBox for codeEditor
                    RichTextBox codeEditor = new System.Windows.Forms.RichTextBox();
     
                    codeEditor.BackColor = System.Drawing.SystemColors.Desktop;
                    codeEditor.ForeColor = System.Drawing.Color.White;
                    codeEditor.Dock = System.Windows.Forms.DockStyle.Fill;
                    codeEditor.Font = new System.Drawing.Font("Verdana", 9.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
                    codeEditor.Location = new System.Drawing.Point(0, 0);
                    codeEditor.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Both;
                    codeEditor.WordWrap = false;
                    codeEditor.Size = new System.Drawing.Size(284, 247);
                    codeEditor.TabIndex = 0;
                    codeEditor.ReadOnly = true;
                    codeEditor.Text = "";
                    tabPage.Controls.Add(codeEditor);
                    return this.tabControl1.TabPages.Count - 1;
                }
            }
            private HostControl CurrentDocumentsHostControl
            {
                get
                {
                    return (HostControl)this.tabControl1.TabPages[CurrentDocumentsDesignIndex].Controls[0];
                }
            }
            private RichTextBox CurrentDocumentsCodeEditor
            {
                get
                {
                    return (RichTextBox)this.tabControl1.TabPages[CurrentDocumentsCodeIndex].Controls[0];
                }
            }
            private LoaderType CurrentMenuSelectionLoaderType
            {
                get
                {
                    if (this.basicDesignerLoaderMenuItem.Checked)
                        return LoaderType.BasicDesignerLoader;
                    else if (this.codeDomDesignerLoaderMenuItem.Checked)
                        return LoaderType.CodeDomDesignerLoader;
                    else
                        return LoaderType.NoLoader;
                }
            }
            private LoaderType CurrentActiveDocumentLoaderType
            {
                get
                {
                    TabPage tabPage = this.tabControl1.TabPages[this.tabControl1.SelectedIndex];
     
                    return (LoaderType)tabPage.Tag;
                }
            }
            private string CurrentDocumentView
            {
                get
                {
                    TabPage tabPage = this.tabControl1.TabPages[this.tabControl1.SelectedIndex];
     
                    if (tabPage.Text.Contains(Strings.Design))
                        return Strings.Design;
                    else
                        return Strings.Code;
                }
            }
     
            private void basicDesignerLoaderMenuItem_Click(object sender, System.EventArgs e)
            {
                this.noLoaderMenuItem.Checked = false;
                this.codeDomDesignerLoaderMenuItem.Checked = false;
                this.basicDesignerLoaderMenuItem.Checked = true;
     
                // Disable all item types except Form
                this.formMenuItem.Enabled = true;
                this.userControlMenuItem.Enabled = false;
                this.componentMenuItem.Enabled = false;
                this.grapherMenuItem.Enabled = false;
            }
     
            private void noLoaderMenuItem_Click(object sender, System.EventArgs e)
            {
                this.noLoaderMenuItem.Checked = true;
                this.codeDomDesignerLoaderMenuItem.Checked = false;
                this.basicDesignerLoaderMenuItem.Checked = false;
     
                // Enable all item types
                this.formMenuItem.Enabled = true;
                this.userControlMenuItem.Enabled = true;
                this.componentMenuItem.Enabled = true;
                this.grapherMenuItem.Enabled = true;
            }
     
            private void codeDomDesignerLoaderMenuItem_Click(object sender, System.EventArgs e)
            {
                this.noLoaderMenuItem.Checked = false;
                this.codeDomDesignerLoaderMenuItem.Checked = true;
                this.basicDesignerLoaderMenuItem.Checked = false;
     
                // Disable all item types except Form
                this.formMenuItem.Enabled = true;
                this.userControlMenuItem.Enabled = false;
                this.componentMenuItem.Enabled = false;
                this.grapherMenuItem.Enabled = false;
            }
     
            private void xmlMenuItem_Click(object sender, System.EventArgs e)
            {
                SwitchToCode(Strings.Xml);
            }
            private void cMenuItem1_Click(object sender, System.EventArgs e)
            {
                SwitchToCode(Strings.CS);
            }
     
            private void vBMenuItem_Click(object sender, System.EventArgs e)
            {
                SwitchToCode(Strings.VB);
            }
     
            private void jMenuItem1_Click(object sender, System.EventArgs e)
            {
                SwitchToCode(Strings.JS);
            }
     
            private void SwitchToCode(string context)
            {
                if (CurrentActiveDocumentLoaderType == LoaderType.NoLoader)
                {
                    MessageBox.Show("Code view is not supported for document loaded without Loaders");
                    return;
                }
     
                if (context == Strings.Xml && CurrentActiveDocumentLoaderType != LoaderType.BasicDesignerLoader)
                {
                    MessageBox.Show("Xml code view is supported only for BasicDesignerLoader");
                    return;
                }
                /*  MODIF: RAJOUT  CONSTANTE  Strings.CPC */
                if ((context == Strings.CS || context == Strings.VB || context == Strings.JS || context == Strings.CPC) && CurrentActiveDocumentLoaderType != LoaderType.CodeDomDesignerLoader)
                {
                    MessageBox.Show(context + " code view is supported only for CodeDomDesignerLoader");
                    return;
                }
     
                HostControl currentHostControl = CurrentDocumentsHostControl;
                RichTextBox codeEditor = CurrentDocumentsCodeEditor;
                if (CurrentActiveDocumentLoaderType == LoaderType.BasicDesignerLoader)
                    codeEditor.Text = ((BasicHostLoader)currentHostControl.HostSurface.Loader).GetCode();
                /*  MODIF: JUMP  Strings.CS, Strings.VB,Strings.JS */
                else if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader && (context == Strings.CS || context == Strings.VB || context == Strings.JS))
                    codeEditor.Text = ((CodeDomHostLoader)currentHostControl.HostSurface.Loader).GetCode(context);
                /*  MODIF: JUMP  Strings.CS, Strings.VB,Strings.JS */
                /*  MODIF: JUMP  Strings.Cpc .ENVOI  du stringbuilder dans richtextbox */
                else if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader && (context == Strings.CPC))
                    codeEditor.Text = sbCpc.ToString();
                int index = CurrentDocumentsCodeIndex;
     
                if (this.tabControl1.SelectedIndex != index)
                {
                    _prevIndex = this.tabControl1.SelectedIndex;
                    this.tabControl1.SelectedIndex = index;
                    _curIndex = index;
                }
            }
     
            private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (CurrentDocumentView == Strings.Design)
                {
                    if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader)
                        this.eMenuItem.Enabled = true;
                    else
                        this.eMenuItem.Enabled = false;
                }
                else
                {
                    if (CurrentActiveDocumentLoaderType == LoaderType.BasicDesignerLoader)
                        SwitchToCode(Strings.Xml);
                    else if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader)
                        SwitchToCode(Strings.CS);
                }
            }
     
            /// <summary>
            /// Persist the code if the host is loaded using a BasicDesignerLoader
            /// </summary>
            private void saveMenuItem_Click(object sender, System.EventArgs e)
            {
                if (CurrentActiveDocumentLoaderType == LoaderType.NoLoader)
                {
                    MessageBox.Show("Cannot persist document created without loaders");
                    return;
                }
     
                if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader)
                {
                    MessageBox.Show("Cannot persist document created using CodeDomDesignerLoader");
                    return;
                }
     
                HostControl currentHostControl = CurrentDocumentsHostControl;
     
                if (CurrentActiveDocumentLoaderType == LoaderType.BasicDesignerLoader)
                    ((BasicHostLoader)currentHostControl.HostSurface.Loader).Save();
     
                this.OutputWindow.RichTextBox.Text += "Saved host.\n";
            }
     
            /// <summary>
            /// Open an xml file that was saved earlier
            /// </summary>
            private void openMenuItem_Click(object sender, System.EventArgs e)
            {
                try
                {
                    string fileName = null;
     
                    // Open File Dialog
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.DefaultExt = "xml";
                    dlg.Filter = "Xml Files|*.xml";
                    if (dlg.ShowDialog() == DialogResult.OK)
                        fileName = dlg.FileName;
     
                    if (fileName == null)
                        return;
     
                    // Create Form
                    _formCount++;
                    HostControl hc = _hostSurfaceManager.GetNewHost(fileName);
                    this.Toolbox.DesignerHost = hc.DesignerHost;
                    TabPage tabpage = new TabPage("Form" + _formCount.ToString() + " - " + Strings.Design);
     
                    if (fileName.EndsWith("xml"))
                        tabpage.Tag = LoaderType.BasicDesignerLoader;
                    else if (fileName.EndsWith("cs") || fileName.EndsWith("vb"))
                        tabpage.Tag = LoaderType.CodeDomDesignerLoader;
     
                    hc.Parent = tabpage;
                    hc.Dock = DockStyle.Fill;
                    this.tabControl1.TabPages.Add(tabpage);
                    this.tabControl1.SelectedIndex = this.tabControl1.TabPages.Count - 1;
                    this.OutputWindow.RichTextBox.Text += "Opened new host.\n";
                }
                catch
                {
                    MessageBox.Show("Error in creating new host", "Shell Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
     
            private void saveAsMenuItem_Click(object sender, System.EventArgs e)
            {
                if (CurrentActiveDocumentLoaderType == LoaderType.NoLoader)
                {
                    MessageBox.Show("Cannot persist document created without loaders");
                    return;
                }
     
                if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader)
                {
                    MessageBox.Show("Cannot persist document created using CodeDomDesignerLoader");
                    return;
                }
     
                HostControl currentHostControl = CurrentDocumentsHostControl;
                ((BasicHostLoader)currentHostControl.HostSurface.Loader).Save(true);
            }
     
            /// <summary>
            /// If the host was loaded using a CodeDomDesignerLoader then we can run it
            /// </summary>
            private void runMenuItem_Click(object sender, System.EventArgs e)
            {
                if (CurrentActiveDocumentLoaderType == LoaderType.NoLoader || CurrentActiveDocumentLoaderType == LoaderType.BasicDesignerLoader)
                {
                    MessageBox.Show("Cannot Run document created without loaders or created using BasicDesignerLoader. To run a document use CodeDomDesignerLoader");
                    return;
                }
     
                HostControl currentHostControl = CurrentDocumentsHostControl;
                ((CodeDomHostLoader)currentHostControl.HostSurface.Loader).Run();
            }
     
            private void exitMenuItem_Click(object sender, System.EventArgs e)
            {
                this.Close();
            }
     
            private void AddTabForNewHost(string tabText, HostControl hc)
            {
                this.Toolbox.DesignerHost = hc.DesignerHost;
                TabPage tabpage = new TabPage(tabText);
                tabpage.Tag = CurrentMenuSelectionLoaderType;
                hc.Parent = tabpage;
                hc.Dock = DockStyle.Fill;
                this.tabControl1.TabPages.Add(tabpage);
                this.tabControl1.SelectedIndex = this.tabControl1.TabPages.Count - 1;
                _hostSurfaceManager.ActiveDesignSurface = hc.HostSurface;
                if (CurrentActiveDocumentLoaderType == LoaderType.CodeDomDesignerLoader)
                    this.eMenuItem.Enabled = true;
                else
                    this.eMenuItem.Enabled = false;
                this.solutionExplorer1.AddFileNode(tabText);
     
            }
     
            private void formMenuItem_Click(object sender, System.EventArgs e)
            {
                try
                {
                    _formCount++;
                    HostControl hc = _hostSurfaceManager.GetNewHost(typeof(Form), CurrentMenuSelectionLoaderType);
                    AddTabForNewHost("Form" + _formCount.ToString() + " - " + Strings.Design, hc);
                }
                catch
                {
                    MessageBox.Show("Error in creating new host", "Shell Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
     
            private void userControlMenuItem_Click(object sender, EventArgs e)
            {
                try
                {
                    _userControlCount++;
                    HostControl hc = _hostSurfaceManager.GetNewHost(typeof(UserControl), CurrentMenuSelectionLoaderType);
                    AddTabForNewHost("UserControl" + _userControlCount.ToString() + " - " + Strings.Design, hc);
                }
                catch
                {
                    MessageBox.Show("Error in creating new host", "Shell Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
     
            private void componentMenuItem_Click(object sender, EventArgs e)
            {
                try
                {
                    _componentCount++;
                    HostControl hc = _hostSurfaceManager.GetNewHost(typeof(Component), CurrentMenuSelectionLoaderType);
                    AddTabForNewHost("Component" + _componentCount.ToString() + " - " + Strings.Design, hc);
                }
                catch
                {
                    MessageBox.Show("Error in creating new host", "Shell Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
     
            private void grapherMenuItem_Click(object sender, EventArgs e)
            {
                try
                {
                    _grapherCount++;
                    HostControl hc = _hostSurfaceManager.GetNewHost(typeof(MyTopLevelComponent), CurrentMenuSelectionLoaderType);
                    AddTabForNewHost("CustomDesigner" + _grapherCount.ToString() + " - " + Strings.Design, hc);
                }
                catch
                {
                    MessageBox.Show("Error in creating new host", "Shell Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
     
            /// <summary>
            /// Perform all the Edit menu options using the MenuCommandService
            /// </summary>
            private void PerformAction(string text)
            {
                if (this.CurrentDocumentView == Strings.Code)
                {
                    MessageBox.Show("This is not in supported code view");
                    return;
                }
     
                if (this.CurrentDocumentsHostControl == null)
                    return;
     
                IMenuCommandService ims = this.CurrentDocumentsHostControl.HostSurface.GetService(typeof(IMenuCommandService)) as IMenuCommandService;
     
                try
                {
                    switch (text)
                    {
                        case "&Cut":
                            ims.GlobalInvoke(StandardCommands.Cut);
                            break;
                        case "C&opy":
                            ims.GlobalInvoke(StandardCommands.Copy);
                            break;
                        case "&Paste":
                            ims.GlobalInvoke(StandardCommands.Paste);
                            break;
                        case "&Undo":
                            ims.GlobalInvoke(StandardCommands.Undo);
                            break;
                        case "&Redo":
                            ims.GlobalInvoke(StandardCommands.Redo);
                            break;
                        case "&Delete":
                            ims.GlobalInvoke(StandardCommands.Delete);
                            break;
                        case "&Select All":
                            ims.GlobalInvoke(StandardCommands.SelectAll);
                            break;
                        case "&Lefts":
                            ims.GlobalInvoke(StandardCommands.AlignLeft);
                            break;
                        case "&Centers":
                            ims.GlobalInvoke(StandardCommands.AlignHorizontalCenters);
                            break;
                        case "&Rights":
                            ims.GlobalInvoke(StandardCommands.AlignRight);
                            break;
                        case "&Tops":
                            ims.GlobalInvoke(StandardCommands.AlignTop);
                            break;
                        case "&Middles":
                            ims.GlobalInvoke(StandardCommands.AlignVerticalCenters);
                            break;
                        case "&Bottoms":
                            ims.GlobalInvoke(StandardCommands.AlignBottom);
                            break;
                        default:
                            break;
                    }
                }
                catch 
                {
                    this.OutputWindow.RichTextBox.Text += "Error in performing the action: " + text.Replace("&", "");
                }
            }
     
            private void ActionClick(object sender, EventArgs e)
            {
                PerformAction((sender as MenuItem).Text);
            }
     
            private void openMenuItem1_Click(object sender, EventArgs e)
            {
                MessageBox.Show("Options can be implemented here");
            }
     
            private void abMenuItem_Click(object sender, EventArgs e)
            {
                MessageBox.Show("Designer Hosting sample. Whidbey ROCKS!");
            }
     
            /** MODIF  AJOUT MENUITEM CPC  */
            private void CPCmenuItem_Click(object sender, EventArgs e)
            {
     
                HostSurface hostSurface = (HostSurface)_hostSurfaceManager.ActiveDesignSurface;
                IDesignerHost host = (IDesignerHost)hostSurface.GetService(typeof(IDesignerHost));
     
                if (host == null)
                    return;
     
                try
                {
                    Type hostType = host.RootComponent.GetType();
                    if (hostType == typeof(Form))
                    {
                        currentFrm = host.RootComponent as Form;
     
                        sbCpc = GenFileTextCpc(currentFrm);
                        SwitchToCode(Strings.CPC);
                    }
                    else
                    {
                        throw new Exception("Undefined Host Type: " + hostType.ToString());
                    }
     
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "  cannot find the control");
                }
     
     
            }
            private StringBuilder GenFileTextCpc(Form frm)
            {
                StringBuilder sb = new StringBuilder();
                WriteProperties(frm, sb);
                foreach (Control ctl in frm.Controls)
                {
                    WriteProperties(ctl, sb);
     
                }
                return sb;
            }
            private void WriteProperties(Control ctl, StringBuilder sb)
            {
     
                if (ctl.GetType() == typeof(Form))
                    sb.AppendLine("fenetre/");
                else if (ctl.GetType() == typeof(Button))
                    sb.AppendLine("bouton/");
                else if (ctl.GetType() == typeof(TextBox))
                    sb.AppendLine("textebloc/");
                else if (ctl.GetType() == typeof(PictureBox))
                    sb.AppendLine("picturebox/");
                else if (ctl.GetType() == typeof(CheckBox))
                    sb.AppendLine("checkbox/");
                PropertyInfo[] pinfos = ctl.GetType().GetProperties();
                foreach (var propinfo in pinfos)
                {
                    Color clr;
                    switch (propinfo.Name)
                    {
                        case "Text":
                            sb.AppendLine(".titre = " + ctl.Text);
                            break;
                        case "Location":
                            sb.AppendLine(".px = " + ctl.Location.X.ToString());
                            sb.AppendLine(".py = " + ctl.Location.Y.ToString());
                            break;
                        case "Size":
                            sb.AppendLine(".tx = " + ctl.Location.X.ToString());
                            sb.AppendLine(".ty = " + ctl.Location.Y.ToString());
                            break;
                        case "ForeColor":
                            clr = ctl.ForeColor;
                            sb.AppendLine(".CouleurTexte  = \"" + clr.R.ToString() + "," + clr.G.ToString() + "," + clr.B.ToString() + "\"");
                            break;
                        case "BackColor":
                            clr = ctl.BackColor;
                            sb.AppendLine(".CouleurFond = \"" + clr.R.ToString() + "," + clr.G.ToString() + "," + clr.B.ToString() + "\"");
                            break;
                        default:
                            break;
                    }
     
                }
                if (ctl.GetType() == typeof(Form))
                    sb.AppendLine("Fin/ fenetre");
                else if (ctl.GetType() == typeof(Button))
                    sb.AppendLine("Fin/ bouton/");
                else if (ctl.GetType() == typeof(TextBox))
                    sb.AppendLine("Fin/ textebloc/");
                else if (ctl.GetType() == typeof(PictureBox))
                    sb.AppendLine("Fin/ picturebox/");
                else if (ctl.GetType() == typeof(CheckBox))
                    sb.AppendLine("Fin/ checkbox/");
            }
            private class Strings
            {
                public const string Design = "Design";
                public const string Code = "Code";
                public const string Xml = "Xml";
                public const string CS = "C#";
                public const string JS = "J#";
                public const string VB = "VB";
                public const string CPC = "CPC";
            }
     
     
     
        }
    }
    N.B : pour une copie du fichier texte CPC sur disque ,tu n'as qu'a rajouter dans le menu File un menuitem pour sauvagarder le contenu du stringbuilder.
    (sb.tostring)

    Bon code...

Discussions similaires

  1. [JAXP] com.sun.xml.parser.ValidatingParser
    Par yolepro dans le forum Format d'échange (XML, JSON...)
    Réponses: 7
    Dernier message: 05/11/2008, 15h36
  2. parser xml
    Par billout dans le forum C++Builder
    Réponses: 4
    Dernier message: 20/11/2003, 11h08
  3. [Servlet] parser la requete
    Par jaimepasteevy dans le forum Servlets/JSP
    Réponses: 3
    Dernier message: 15/10/2003, 16h43
  4. Parser XML
    Par miloux32 dans le forum XML/XSL et SOAP
    Réponses: 4
    Dernier message: 18/07/2003, 03h17
  5. [langage] Continuer a parser une ligne
    Par D[r]eadLock dans le forum Langage
    Réponses: 5
    Dernier message: 30/09/2002, 18h49

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