将单词拖放到图WindowsForms中

时间:2019-05-25 12:23:03

标签: c# visual-studio drag-and-drop windows-forms-designer

当对Word文档中的字符串类型使用拖放功能时,如何在C#中制作图形?我的想法是,我想制作一个图形,以表示应该拖放的单词的长度。

在我编写的程序中,功能是拖放数字并制作一个图形,以显示其值之间的差异。

例如,我想在启动程序时将“书,笔”拖放到WindowsForms上已经存在的图形上,并且“条形图”反映的是第一列大于第二列。书-> 4个字母; Pen-> 3个字母

public class Grafic: Control
{
    int[] valori;

    private void Grafic_DragDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(string)))
        {
            string valoriString =
                (string)e.Data.GetData(typeof(string));
            //MessageBox.Show(valoriString);

            Valori = valoriString
                    .Split(',')
                    .Select(val => int.Parse(val))
                    .ToArray();
        }
    }        

这是我的问题,我必须以某种方式修改int.Parse(val)的代码部分。

我希望图形接受字符串类型并反映出我的描述。

1 个答案:

答案 0 :(得分:0)

以下是一些入门指南:

public partial class Grafic : Control
{

    private SortedDictionary<int, int> WordLengthCounts = new SortedDictionary<int, int>();

    public Grafic()
    {
        InitializeComponent();
        this.DragEnter += Grafic_DragEnter;
        this.DragDrop += Grafic_DragDrop;
        this.Paint += Grafic_Paint;
    }

    private void Grafic_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = e.Data.GetDataPresent(typeof(string)) ? DragDropEffects.All : DragDropEffects.None;
    }

    private void Grafic_DragDrop(object sender, DragEventArgs e)
    {
        string input = (string)e.Data.GetData(typeof(string));
        // Regex by TheCodeKing: https://stackoverflow.com/a/7311811/2330053
        var matches = System.Text.RegularExpressions.Regex.Matches(input, @"((\b[^\s]+\b)((?<=\.\w).)?)");
        foreach (var match in matches)
        {
            int wordLength = match.ToString().Length;
            if(!WordLengthCounts.ContainsKey(wordLength))
            {
                WordLengthCounts.Add(wordLength, 1);
            }
            else
            {
                WordLengthCounts[wordLength]++;
            }
        }
        this.Invalidate();
    }

    private void Grafic_Paint(object sender, PaintEventArgs e)
    {
        Graphics G = e.Graphics;
        foreach(var wordLengthCount in WordLengthCounts)
        {
            Console.WriteLine("Length: " + wordLengthCount.Key.ToString() + ", Count: " + wordLengthCount.Value.ToString());

            // ... put in your drawing code to visualize this data ...

        }
    }

}