将值从Windows窗体传递到控制台应用程序

时间:2012-06-08 15:05:42

标签: c# .net soap server-side

所以我有一个程序通过Windows窗体接收用户凭据,现在通过MessageBox我正在显示用户输入,我想要做的是将它传递到我的控制台应用程序,以便用户输入然后在控制台应用程序中继续正确的凭据,我该怎么做呢?

4 个答案:

答案 0 :(得分:1)

您可能需要添加while循环以在控制台应用程序中查找txt文件。在Windows窗体应用程序中,您可以将成功或失败消息写入txt文件。 (为安全性添加加密)当您记下控制台应用程序应该读取的信息并从那里继续加密时。

Algorithm:
1.console application start
2. console app while loop until txt file detected
3. forms app show input screen
4. user enter credential
5. write success or failure into txt file
6. read txt file
7. continue based on credential result
8. Remove txt file

由于表单也在控制台应用程序项目中(我假设它来自你的措辞),你可以执行以下操作

class Program
{
    public static object abc;
    static void Main(string[] args)
    {
        //do something here if required
        Form1 frm = new Form1();
        if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            //login success do what ever on success
            Console.WriteLine("Login success");
            Console.WriteLine(abc.ToString());
        }
        else
        {
            Console.WriteLine("Login failure");
            Console.WriteLine(abc.ToString());
            //login failure
        }
        Console.ReadLine();
    }
}

以及登录表单类中的登录按钮单击事件

 private void Login_Click(object sender, EventArgs e)
    {
        if(true)
        {
            Program.abc = "any success object here";
            //on successful login
        this.DialogResult= System.Windows.Forms.DialogResult.OK;
        }
        else
        {
            Program.abc = "any failure object here";
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }

谢谢,

也先

答案 1 :(得分:0)

您可以在表单应用中托管wcf服务。然后使控制台应用程序成为客户端。使用wcf创建面向服务的系统非常简单。有关教程,请参阅here。如果你采用这种方法,你会学到很多东西

答案 2 :(得分:0)

将IPC(进程间通信)与命名管道一起使用。在两个进程之间易于实现,请查看http://msdn.microsoft.com/en-us/library/bb546085.aspx

答案 3 :(得分:0)

基本上,您可能必须使用一些本机Windows API函数(Alloc / FreeConsole)并使用WinForms控制器。

半伪代码:

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeConsole();

//--- form code
if (Do_validation() && AllocConsole())
{
    this.Hide();
    this.ShowInTaskbar = false;
    Enter_Console_Code();
    FreeConsole();
    System.Threading.Thread.Sleep(50); //FreeConsole sometimes doesn't finish closing straight away which means your form flickers to the front and then minimizes.
    this.ShowInTaskbar = true;        
    this.Show(); 
}
//---

private void Enter_Console_Code()
{ 
    string line = string.Empty;
    while ((line = Console.ReadLine()) != "q")
        Console.WriteLine(line); //pointless code ftw!
}

本代码的作用基本上是执行“GUI”验证步骤,然后如果成功则尝试为应用程序分配控制台。一旦分配了控制台,它就会通过完全隐藏GUI并仅显示新控制台进入“控制台模式”(顺便关闭控制台关闭应用程序)。执行“控制台模式”代码,然后关闭控制台并返回GUI。

相关问题