Please note: If this is a Windows Forms application, having a while
loop inside a button click event handler is somewhat problematic - the application message queue is not being processed while the handler is running. Ideally, the content of the while
loop should be run every N seconds using System.Windows.Forms.Timer
object instead. Then, when a 'stop' button or key is pressed, you would call terminal.SendToServer("q")
to terminate the top
command.
Now, in order to keep the code simple, I will keep the while
loop but call Application.DoEvents()
to process the message queue, and a field to indicate to the loop that the top
command should end:
public partial class Form1 : Form
{
private bool TopShouldEnd;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Ssh client = new Ssh();
client.Connect("192.168.150.129");
// authenticate
client.Login("reza", "1");
// start virtual termina (80x25)
int columns = 80;
int rows = 25;
VirtualTerminal terminal = client.StartVirtualTerminal(null, columns, rows);
// send 'top' command to the server
terminal.SendToServer("top\n");
//terminal.SendToServer("q");
// the 'top' command will run forever until terminated (by 'q' key, for example)
while (true)
{
// process WinForm application's events (handle button clicks)
Application.DoEvents();
// process any available incoming data for 2 seconds
TerminalState state = terminal.Process(2000);
if (state == TerminalState.Disconnected)
break;
if (state == TerminalState.DataReceived)
{
// display the current terminal screen content
string[] lines = terminal.Screen.GetRegionText(0, 0, columns, rows);
string result = string.Join("\n", lines);
Console.WriteLine(result);
if (TopShouldEnd)
{
// exit the 'top' command
terminal.SendToServer("q");
break;
}
}
}
// end the SSH session
terminal.SendToServer("exit\n");
terminal.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
TopShouldEnd = true;
}
}