• 微软原版系统

  • 一键重装系统

  • 纯净系统

  • 在线技术客服

魔法猪系统重装大师 一键在线制作启动 U 盘 PE 系统 用一键重装的魔法拯救失去灵魂的系统
当前位置:首页 > 教程 > 电脑教程

动态执行页面输入代码

时间:2015年04月02日 15:45:24    来源:魔法猪系统重装大师官网    人气:7396

前台代码:TextBox实现换行  加上 TextWrapping="Wrap" AcceptsReturn="True" 两个属性就行了。

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="357" Width="582">







 

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.IO;

namespace WpfAssembly
{
///


/// Window1.xaml 的交互逻辑
///

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
CodeDriver driver = new CodeDriver();
bool isError;
textBlock1.Text = driver.ComplileAndRun(textBox1.Text,out isError);//调用执行代码的类
if (isError)
{
textBlock1.Background = Brushes.Red;
}
else
{
textBlock1.Background = Brushes.NavajoWhite;
}
}
}
public class CodeDriver
{
private string prefix = "using System;" +
"public static class Driver" +
"{" +
"public static void Run()" +
"{";
private string postfix = "}" + "}";
public string ComplileAndRun(string input, out bool hasError)
{
hasError = false;
string returnData = null;
CompilerResults results = null;
using (CSharpCodeProvider provider = new CSharpCodeProvider())//c#代码生成器和编译器的实例
{
CompilerParameters options = new CompilerParameters();
options.GenerateInMemory = true;//是否从内存输出
StringBuilder sb = new StringBuilder();
sb.Append(prefix);
sb.Append(input);
sb.Append(postfix);

results = provider.CompileAssemblyFromSource(options, sb.ToString());//向编译器输入代码字符

}
if (results.Errors.HasErrors)//代码运行是否正常
{
hasError = true;
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
sb.AppendFormat("{0} {1}", error.Line, error.ErrorText);
}
returnData = sb.ToString();
}
else
{
TextWriter tw = Console.Out;
StringWriter sw = new StringWriter();
Console.SetOut(sw);//接受输出的字符串
Type driverType = results.CompiledAssembly.GetType("Driver");//反射获取Driver类
//指定执行函数的参数列表
driverType.InvokeMember("Run", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, null);

Console.SetOut(tw);
returnData = sw.ToString();
}
return returnData;
}
}
}

动态,执行,页面,输入,代码,前台,代码,TextBox,
栏目:电脑教程 阅读:1000 2023/12/27
Win7教程 更多>>
U盘教程 更多>>
Win10教程 更多>>
魔法猪学院 更多>>

Copyright © 2015-2023 魔法猪 魔法猪系统重装大师

本站发布的系统仅为个人学习测试使用,请在下载后24小时内删除,不得用于任何商业用途,否则后果自负,请支持购买微软正版软件。

在线客服 查看微信 返回顶部