将该代码转化当C#窗体程序中using System; namespace VigenereCipher { class Program { static void Main(string[] args) { Console.WriteLine("请选择操作:\n1. 加密\n2. 解密"); int choice = int.Parse(Console.ReadLine()); Console.WriteLine("请输入明文/密文:"); string text = Console.ReadLine(); Console.WriteLine("请输入密钥:"); string key = Console.ReadLine(); if (choice == 1) { string cipherText = Encrypt(text, key); Console.WriteLine("加密后的结果为:" + cipherText); } else if (choice == 2) { string plainText = Decrypt(text, key); Console.WriteLine("解密后的结果为:" + plainText); } else { Console.WriteLine("输入错误!"); } } static string Encrypt(string text, string key) { string cipherText = ""; int keyIndex = 0; for (int i = 0; i < text.Length; i++) { char c = text[i]; int offset = key[keyIndex] - 'A'; char encryptedChar = (char)((c + offset) % 256); cipherText += encryptedChar; keyIndex = (keyIndex + 1) % key.Length; } return cipherText; } static string Decrypt(string text, string key) { string plainText = ""; int keyIndex = 0; for (int i = 0; i < text.Length; i++) { char c = text[i]; int offset = key[keyIndex] - 'A'; char decryptedChar = (char)((c - offset + 256) % 256); plainText += decryptedChar; keyIndex = (keyIndex + 1) % key.Length; } return plainText; } } }
时间: 2024-01-23 21:01:35 浏览: 94
以下是将该代码转化为C#窗体程序的示例代码:
```csharp
using System;
using System.Windows.Forms;
namespace VigenereCipher
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void encryptButton_Click(object sender, EventArgs e)
{
string text = inputTextBox.Text;
string key = keyTextBox.Text;
string cipherText = Encrypt(text, key);
outputTextBox.Text = cipherText;
}
private void decryptButton_Click(object sender, EventArgs e)
{
string text = inputTextBox.Text;
string key = keyTextBox.Text;
string plainText = Decrypt(text, key);
outputTextBox.Text = plainText;
}
static string Encrypt(string text, string key)
{
string cipherText = "";
int keyIndex = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
int offset = key[keyIndex] - 'A';
char encryptedChar = (char)((c + offset) % 256);
cipherText += encryptedChar;
keyIndex = (keyIndex + 1) % key.Length;
}
return cipherText;
}
static string Decrypt(string text, string key)
{
string plainText = "";
int keyIndex = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
int offset = key[keyIndex] - 'A';
char decryptedChar = (char)((c - offset + 256) % 256);
plainText += decryptedChar;
keyIndex = (keyIndex + 1) % key.Length;
}
return plainText;
}
}
}
```
在窗体设计器中添加一个`TextBox`控件用于输入明文/密文,一个`TextBox`控件用于输入密钥,一个`TextBox`控件用于显示加密/解密结果,以及两个`Button`控件分别用于加密和解密操作。
然后,将`encryptButton_Click`和`decryptButton_Click`事件处理程序中的代码替换为原来的`Main`方法中的代码即可。注意修改控件的名称以与代码中的名称相匹配。
阅读全文
相关推荐



















