2009-10-26 3 views

risposta

6

si dovrebbe essere in grado di aggiungere un riferimento per System.Windows.Forms e poi essere pronti per partire. Potrebbe anche essere necessario applicare STAThreadAttribute al punto di ingresso dell'applicazione.

using System.Windows.Forms; 

class Program 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 
     MessageBox.Show("hello"); 
    } 
} 

... più complessa ...

using System.Windows.Forms; 

class Program 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 
     var frm = new Form(); 
     frm.Name = "Hello"; 
     var lb = new Label(); 
     lb.Text = "Hello World!!!"; 
     frm.Controls.Add(lb); 
     frm.ShowDialog(); 
    } 
} 
4

Sì, è possibile inizializzare un modulo nella console. Aggiungere un riferimento a System.Windows.Forms e utilizzare il seguente codice di esempio:

System.Windows.Forms.Form f = new System.Windows.Forms.Form(); 
f.ShowDialog(); 
+0

Posso ottenere alcuni commenti sui downmods? –

+0

Perché è stato downvoted? Potrebbe non essere una buona pratica, ma è sicuramente possibile. –

+0

Funzionerà senza l'attributo STAThread? –

1

Si può provare questo

using System.Windows.Forms; 

[STAThread] 
static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.Run(new MyForm()); 
} 

Bye.

4

La risposta comune:

[STAThread] 
static void Main() 
{  
    Application.Run(new MyForm()); 
} 

Alternatives (tratto da here) se, per esempio - si desidera avviare una forma da un thread diverso da quello della principale dell'applicazione:

Thread t = new Thread(new ThreadStart(StartNewStaThread)); 

// Make sure to set the apartment state BEFORE starting the thread. 
t.ApartmentState = ApartmentState.STA; 
t.Start(); 

private void StartNewStaThread() { 
    Application.Run(new Form1()); 
} 

.

Thread t = new Thread(new ThreadStart(StartNewStaThread)); 
t.Start(); 

[STAThread] 
private void StartNewStaThread() { 
    Application.Run(new Form1()); 
}