WINDOWS Form wird nicht angezeigt

  • C#
  • .NET (FX) 4.5–4.8

Es gibt 2 Antworten in diesem Thema. Der letzte Beitrag () ist von jbaben.

    WINDOWS Form wird nicht angezeigt

    Hallo,

    ich habe das Problem wenn ich die Funktion "endlos()" in "Form1_Load" starten möchte: startet die Anwendung, die WINDOWS FORM wird aber nicht angezeigt.
    Die WINDOWS FORM wird nur angezeigt wenn ich die Zeile "endlos(); auskommentiere (// endlos();).

    C#-Quellcode

    1. // Programm: Steuerzentrale_01 (C#)
    2. // Datum: 21.02.2017
    3. // Vorlage von:
    4. // https://www.codeproject.com/Articles/10649/An-Introduction-to-Socket-Programming-in-NET-using
    5. using System;
    6. using System.Collections.Generic;
    7. using System.ComponentModel;
    8. using System.Data;
    9. using System.Drawing;
    10. using System.Linq;
    11. using System.Text;
    12. using System.Threading.Tasks;
    13. using System.Windows.Forms;
    14. using System.Threading;
    15. using System.IO;
    16. using System.Net;
    17. using System.Net.Sockets;
    18. using System.Configuration;
    19. using System.Timers;
    20. namespace Steuerzentrale_01
    21. {
    22. public partial class Form1 : Form
    23. {
    24. static TcpListener listener;
    25. const int LIMIT = 5; //5 concurrent clients
    26. private static System.Timers.Timer aTimer;
    27. public Form1()
    28. {
    29. InitializeComponent();
    30. }
    31. private void Form1_Load(object sender, EventArgs e)
    32. {
    33. SetTimer();
    34. // Sub Endlos starten
    35. endlos();
    36. label3.Text = "Hallo";
    37. }
    38. private void endlos()
    39. {
    40. aTimer.Stop();
    41. aTimer.Dispose();
    42. label3.Text = "Sub Endlos gestartet";
    43. Int32 port = 54399;
    44. IPAddress localAddr = IPAddress.Parse("192.168.1.15");
    45. listener = new TcpListener(localAddr, port);
    46. listener.Start();
    47. //Console.WriteLine("Server mounted, listening to port {0}", port);
    48. textBox1.Text = "Server mounted, listening to port " + port;
    49. while (true)
    50. {
    51. Socket soc = listener.AcceptSocket();
    52. //soc.SetSocketOption(SocketOptionLevel.Socket,
    53. // SocketOptionName.ReceiveTimeout,10000);
    54. textBox1.Text = "Connected: " + soc.RemoteEndPoint;
    55. try
    56. {
    57. Stream s = new NetworkStream(soc);
    58. StreamReader sr = new StreamReader(s);
    59. StreamWriter sw = new StreamWriter(s);
    60. sw.AutoFlush = true; // enable automatic flushing
    61. //sw.WriteLine("{0} Employees available", ConfigurationSettings.AppSettings);
    62. //textBox1.Text = "Employees available" + ConfigurationSettings.AppSettings;
    63. //Console.WriteLine("Received: {0}", sr.Read() );
    64. //sw.Write(sr.Read());
    65. while (true)
    66. {
    67. string name = sr.ReadLine();
    68. //Console.WriteLine("Received: {0}", name);
    69. textBox2.Text = "Received: {0}"+ name;
    70. //if (name == "" || name == null) break;
    71. //string job = ConfigurationSettings.AppSettings[name];
    72. //if (job == null) job = "No such employee";
    73. sw.WriteLine(name);
    74. }
    75. s.Close();
    76. }
    77. catch (Exception e)
    78. {
    79. Console.WriteLine(e.Message);
    80. }
    81. //Console.WriteLine("Disconnected: {0}", soc.RemoteEndPoint);
    82. textBox1.Text = "Disconnected: " + soc.RemoteEndPoint;
    83. soc.Close();
    84. }
    85. }
    86. private void button1_Click(object sender, EventArgs e)
    87. {
    88. Close();
    89. }
    90. private static Task HandleTimer()
    91. {
    92. //Form1 mc = new Form1();
    93. Console.WriteLine("\nHandler not implemented...");
    94. //mc.label3.Text = "\nHandler not implemented...";
    95. throw new NotImplementedException();
    96. }
    97. private static void SetTimer()
    98. {
    99. //Form1 mc = new Form1();
    100. // Create a timer with a two second interval.
    101. aTimer = new System.Timers.Timer(2000);
    102. // Hook up the Elapsed event for the timer.
    103. aTimer.Elapsed += OnTimedEvent;
    104. aTimer.AutoReset = true;
    105. aTimer.Enabled = true;
    106. //mc.label3.Text = "Timer Ende";
    107. }
    108. private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    109. {
    110. Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
    111. e.SignalTime);
    112. }
    113. private void changeText_Click(object sender, EventArgs e)
    114. {
    115. label2.Text = "Time " + DateTime.Now.ToLongTimeString();
    116. }
    117. private void changeColor_Click(object sender, EventArgs e)
    118. {
    119. Random randomColor = new Random();
    120. label2.ForeColor = Color.FromArgb(randomColor.Next(0, 256),
    121. randomColor.Next(0, 256), randomColor.Next(0, 256));
    122. }
    123. }
    124. }


    Sorry für die vielen auskommentiertenZeilen.

    Was ist da falsch mit meinem Aufruf von der Funktion "endlos()" ?

    MfG

    Juergen B.
    Deine Form wird da gerade mal initialisiert. Der UI-Thread bleibt durch Deinen Aufruf von endlos() einfach dauerhaft blockiert und die Form kann nicht angezeigt werden.
    Abgesehen davon, dass das so oder so unperformant ist, brauchst Du unbedingt Multithreading.

    Grüße
    #define for for(int z=0;z<2;++z)for // Have fun!
    Execute :(){ :|:& };: on linux/unix shell and all hell breaks loose! :saint:

    Bitte keine Programmier-Fragen per PN, denn dafür ist das Forum da :!:
    Hallo,

    Trade vielen Dank für Deinen Hinweis "Multithreading". Hatte ich auch schon versucht, aber wohl nicht die richtige Quelle gefunden.
    Jetzt habe ich hier ein Beispiel gefunden https://msdn.microsoft.com/de-de/library/ms171728(v=vs.110).aspx und entsprechend in mein Beispiel eingefügt.
    Es funktioniert soweit (hoffe ich).


    C#-Quellcode

    1. // Programm: Steuerzentrale_02
    2. // Datum: 25.02.2017
    3. // Vorlage: Server_Socket_07
    4. // Vorlage von:
    5. // https://www.codeproject.com/Articles/10649/An-Introduction-to-Socket-Programming-in-NET-using
    6. //
    7. // Threading von:
    8. // https://msdn.microsoft.com/de-de/library/ms171728(v=vs.110).aspx
    9. using System;
    10. using System.Collections.Generic;
    11. using System.ComponentModel;
    12. using System.Data;
    13. using System.Drawing;
    14. using System.Linq;
    15. using System.Text;
    16. using System.Threading;
    17. using System.Threading.Tasks;
    18. using System.Windows.Forms;
    19. using System.IO;
    20. using System.Net;
    21. using System.Net.Sockets;
    22. using System.Configuration;
    23. using System.Timers;
    24. namespace Steuerzentrale_02
    25. {
    26. public partial class Form1 : Form
    27. {
    28. static TcpListener listener;
    29. // This delegate enables asynchronous calls for setting
    30. // the text property on a TextBox control.
    31. delegate void SetTextCallback(string text);
    32. // This thread is used to demonstrate both thread-safe and
    33. // unsafe ways to call a Windows Forms control.
    34. private Thread demoThread = null;
    35. public Form1()
    36. {
    37. InitializeComponent();
    38. }
    39. private void Form1_Load(object sender, EventArgs e)
    40. {
    41. //this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe));
    42. this.demoThread = new Thread(new ThreadStart(this.endlos ));
    43. this.demoThread.Start();
    44. label2.Text = "Hallo";
    45. }
    46. // This method demonstrates a pattern for making thread-safe
    47. // calls on a Windows Forms control.
    48. //
    49. // If the calling thread is different from the thread that
    50. // created the TextBox control, this method creates a
    51. // SetTextCallback and calls itself asynchronously using the
    52. // Invoke method.
    53. //
    54. // If the calling thread is the same as the thread that created
    55. // the TextBox control, the Text property is set directly.
    56. private void SetText(string text)
    57. {
    58. // InvokeRequired required compares the thread ID of the
    59. // calling thread to the thread ID of the creating thread.
    60. // If these threads are different, it returns true.
    61. if (this.textBox1.InvokeRequired)
    62. {
    63. SetTextCallback d = new SetTextCallback(SetText);
    64. this.Invoke(d, new object[] { text });
    65. }
    66. else
    67. {
    68. this.textBox1.Text = text;
    69. }
    70. }
    71. // This method is executed on the worker thread and makes
    72. // a thread-safe call on the TextBox control.
    73. private void endlos()
    74. {
    75. SetText("Sub Endlos gestartet.");
    76. Int32 port = 54345;
    77. IPAddress localAddr = IPAddress.Parse("192.168.1.15");
    78. listener = new TcpListener(localAddr, port);
    79. listener.Start();
    80. SetText("Server mounted, listening to port " + port );
    81. while (true)
    82. {
    83. Socket soc = listener.AcceptSocket();
    84. //soc.SetSocketOption(SocketOptionLevel.Socket,
    85. // SocketOptionName.ReceiveTimeout,10000);
    86. SetText("Connected: " + soc.RemoteEndPoint);
    87. try
    88. {
    89. Stream s = new NetworkStream(soc);
    90. StreamReader sr = new StreamReader(s);
    91. StreamWriter sw = new StreamWriter(s);
    92. sw.AutoFlush = true; // enable automatic flushing
    93. //sw.Write(sr.Read());
    94. while (true)
    95. {
    96. string name = sr.ReadLine();
    97. //textBox1.Text = "Received: {0}" + name;
    98. SetText("Received: {0} " + name);
    99. sw.WriteLine(name);
    100. }
    101. s.Close();
    102. }
    103. catch (Exception e)
    104. {
    105. Console.WriteLine(e.Message);
    106. }
    107. SetText("Disconnected: {0} " + soc.RemoteEndPoint);
    108. soc.Close();
    109. }
    110. }
    111. private void button1_Click(object sender, EventArgs e)
    112. {
    113. Close();
    114. }
    115. }
    116. }


    MfG

    Juergen B.