注册 登录
编程论坛 C# 论坛

记事本查找功能问题

步向巅峰 发布于 2014-05-10 17:42, 677 次点击
做记事本,卡到查找了,求教!!!
查找功能相关代码及记事本附件,求大神指教,怎么把我的查找窗体关掉还不影响使用
主窗体:
    public partial class FrmNote : Form
    {
        private FrmFind ff;
        public FrmNote()
        {
            InitializeComponent();
            ff = new FrmFind();
            ff.Show(this);
            //ff.Hide();     --查找窗体不能关闭,一旦关闭,再查找的时候就出现“未将对象引用设置到对象的实例”异常
        }
        private void 查找ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ff = new FrmFind();
            ff.Show();
        }
         //查找方法
        public int currentPos=-1;//初始化光标当前位置
        int findPos;//光标开始查找的位置
        public void Search(string s)
        {
            
            //获取光标开始查找的位置
            if (currentPos == -1)
            {
                findPos = tbContent.SelectionStart;
            }
            else
            {
                //获得当前光标位置,并设置新的光标位置,用于查找下一处
                findPos = currentPos + s.Length;
            }
            //判断是否查找到
            currentPos = tbContent.Text.IndexOf(s,findPos);//从findPos处开始查找文本s,查找到则返回索引位置value,否则返回-1,value的索引是选中文本开头
            
            if (currentPos == -1)
            {
                MessageBox.Show("找不到 “" + s+"”", "记事本", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //选中查找文本
                tbContent.Select(currentPos, s.Length);
            }

        }
    }
查找窗体:
   public partial class FrmFind : Form
    {
        private FrmNote fn;
        public FrmFind()//构造函数
        {
            InitializeComponent();

        }
        private void FrmFind_Load(object sender, EventArgs e)
        {
            //使标题栏图标不显示
            this.ShowIcon = false;
            this.Activate();

            this.btnNext.Enabled = false;
        }

        public string str = "";
        private void btnNext_Click(object sender, EventArgs e)
        {
            //获得FrmNote窗体的引用
            fn = this.Owner as FrmNote;
            str = fn.tbContent.Text;
            fn.Search(tbFind.Text);
            
        }
    }
主窗体设计器:
 public System.Windows.Forms.TextBox tbContent;
记事本
3 回复
#2
步向巅峰2014-05-10 17:44
哎,我咋看不到我发的附件呢?
只有本站会员才能查看附件,请 登录
#3
yhlvht2014-05-10 22:56
主窗体这3句是木有用滴
public FrmNote()
{
    InitializeComponent();
    //ff = new FrmFind();
    //ff.Show(this);
    //ff.Hide();
}
主窗体查找菜单的click事件,把this传过去
private void 查找ToolStripMenuItem_Click(object sender, EventArgs e)
{
    ff = new FrmFind(this);
    ff.Show();
}
查找窗体的构造函数,将传过来的参数赋值到全局变量fn
public FrmFind(FrmNote fn)//构造函数
{
    InitializeComponent();
    this.fn = fn;
}
btnNext的click事件中,fn就可以直接使用了
private void btnNext_Click(object sender, EventArgs e)
{
    //获得FrmNote窗体的引用
    //fn = this.Owner as FrmNote;
    str = fn.tbContent.Text;
    fn.Search(tbFind.Text);         
}
#4
步向巅峰2014-05-11 11:13
谢谢了,讲的很明白,我试了试,确实如此
1