C# Winform 入门(1)之跨线程调用,程序说话

发布于:2025-04-02 ⋅ 阅读:(26) ⋅ 点赞:(0)

首先我们要知道,跨线程使用让文本显示在文本框中,然后进行程序读取。这期间我们需要调用Speech。 所用到的控件是  button  textbox

效果展示


1.声明方法

void thread_control()
{
    List<string> list = new List<string>();
    list.Add("这是一段由线程修改的控件文本\r\n");
    list.Add("跨线程的操作,你很快就能理解了");
    for(int i = 0; i < 2; i++)
    {
        txtbook.Text += list[i];
        Thread.Sleep(1500);
    }
} 

2.Appear 显示调用

 private void Appeartxt_Click(object sender, EventArgs e)
 {
     new Thread(thread_control).Start();
 }

3.声明实例化Speech

 SpeechSynthesizer synthesizer=new SpeechSynthesizer();
 string word;

4.Speaking 按钮实现

 private void speaktxt_Click(object sender, EventArgs e)
 {
     if(txtbook.Text!="")
     {
         word= txtbook.Text;
     }
     else
     {
         word = "请先输入文字";
     }
     synthesizer.SpeakAsync(word);
 }

5.textbox 回车代替按键

   private void txtbook_KeyDown(object sender, KeyEventArgs e)
   {
       if (e.KeyCode == Keys.Enter)
       {
           this.speaktxt.Focus();
           this.speaktxt_Click (sender, e);
       }
   }

6.跨线程调用

CheckForIllegalCrossThreadCalls=false;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech;
using System.Speech.Synthesis;
using System.Threading;

namespace _01.Speak
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls=false;
        }
        //右键添加引用 =>  引入System.Speech
        //synthesizer 综合器
        SpeechSynthesizer synthesizer=new SpeechSynthesizer();
        string word;
        private void speaktxt_Click(object sender, EventArgs e)
        {
            if(txtbook.Text!="")
            {
                word= txtbook.Text;
            }
            else
            {
                word = "请先输入文字";
            }
            synthesizer.SpeakAsync(word);
        }
        void thread_control()
        {
            List<string> list = new List<string>();
            list.Add("这是一段由线程修改的控件文本\r\n");
            list.Add("跨线程的操作,你很快就能理解了");
            for(int i = 0; i < 2; i++)
            {
                txtbook.Text += list[i];
                Thread.Sleep(1500);
            }
        }
        //按回车键,直接Speaking
        private void txtbook_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.speaktxt.Focus();
                this.speaktxt_Click (sender, e);
            }
        }
        //显示加载文字
        private void Appeartxt_Click(object sender, EventArgs e)
        {
            new Thread(thread_control).Start();
        }
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到