且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#如何将控制台应用程序算法转换为Windows窗体应用程序?

更新时间:2023-02-08 17:52:25

一个愚蠢的应用程序,但想必您知道这一点.该算法对任何事情都没有用.

控制台和窗口化桌面应用程序的使用范例有所不同,因此,与其说是转换",还不如说是在两种情况下如何呈现核心算法.在这种情况下,列表框和按钮才有意义,而不是Console.WriteLine,您的算法代码应调用提供的回调,该回调将项目添加到列表中(在UI线程中).

但是,这里存在一个更深层次的问题:您的算法不能保证在合理的时间内完成(取决于您将stringLength设置为何种值),并且无法将其取消.这在控制台领域是可以的,您可以在其中按Ctrl + C退出无限进程,但是启动永不终止调用的按钮将挂起您的应用程序.您要么需要限制stringLength的输入,要么考虑在后台线程中运行不确定的进程.
This is a silly application, but presumably you know that. That algorithm''s not useful for anything.

Console and windowed desktop applications have somewhat different use paradigms, so it isn''t so much a case of ''converting'' as working out how your core algorithm should be presented in the two cases. In this case a list box and a button makes sense, and instead of Console.WriteLine, your algorithm code should call a supplied callback which adds items to a list (in the UI thread).

There''s a deeper problem here though: your algorithm is not guaranteed to finish in a reasonable time (depending on what you set stringLength to be) and cannot be cancelled. That''s ok in console land, where you can Ctrl+C your way out of an infinite process, but a button that starts a never-terminating call will hang your application. You either need to limit the input of stringLength or consider running the indefinite process in a background thread.


算法保持不变-不可能在合理的时间内帮助您蛮力攻击密码值得庆幸的是,您需要以不同的方式输出它们:而不是Console.Writeline,您需要以某种方式将它们传递回调用过程":通过将ListBox传递给您的类(不好的),然后传递给每个通过事件(更好)将字符串返回给调用者,或者组装完成后传递回的字符串集合(简单,但更新显示的过程很烦人).

实际显示每个字符串很简单:
The algorithm remains the same - unlikely to help you brute force attack a password in a reasonable time period, thankfully - all you need is to output them differently: instead of Console.Writeline, you need to pass them back to the "calling process" in some way: either by passing a ListBox through to your class (bad), passing each string back to the caller via an event (better), or by assembling a collection of strings which you pass back when you complete (simple, but annoyingly slow to update the display).

To actually display each string is simple:
MyListBox.Items.Add(myNewString);

可以做到...