C# TreeNode control, how do I run a program when node is clicked?
I'm creating an application launcher for our company and I woul开发者_JAVA百科d like to use the TreeNode control (we have 100s of network applications that need a structure), when a user clicks a Node (Example: Application 1) then I would like to run the program on it's own i.e. the app launcher isn't waiting for it to close etc.
How would I do this? All I have currently is the TreeNode structure in AD with no code behind it apart from:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
}
Many thanks
You can use the static Process method Start()
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
// Starts Internet Explorer
Process.Start("iexplore.exe");
// Starts the application with the same name as the TreeNode clicked
Process.Start(e.Node.Text);
}
If you wish to pass parameters too then look at using the ProcessStartInfo class.
The only delay you will get, is the waiting for the process to start. You're code won't block while the program is running.
I'd suggest at least requiring a double-click or
Enter
keypress to launch the app, instead of mere selection. Otherwise, what happens when the user just clicks to give focus, or navigates the tree with the arrow keys? Chaos.The TreeViewEventArgs is where you find what node was affected:
e.Node
Ian already pointed out how you can launch a process.
using the ProcessStartInfo let you have more control over the app
when creating your TreeView nodes, place the full path to the app inside each of TreeNode.Tag property and retrieve it to run your process
using System.Diagnostics;
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
//Retrieving the node data
TreeNode myClickedNode = (TreeNode)sender;
//The pointer to your new app
ProcessStartInfo myAppProcessInfo = new ProcessStartInfo(myClickedNode.Tag);
//You can set how the window of the new app will start
myAppProcessInfo.WindowStyle = ProcessWindowStyle.Maximized;
//Start your new app
Process myAppProcess = Process.Start(myAppProcessInfo);
//Using this will put your TreeNode app to sleep, something like System.Threading.Thread.Sleep(int miliseconds) but without the need of telling the app how much it will wait.
myAppProcess.WaitForExit();
}
For all properties look at MSDN ProcessStartInfo Class and MSDN Process Class
精彩评论