#region 필드
        /// <summary>
        /// 다음 단어를 찾을 때 Index 위치
        /// </summary>
        int seekIndex = 0;
        #endregion

#region public method
        /// <summary>
        /// 해당 키워드들을 원하는 Color로 지정해줍니다.
        /// </summary>
        /// <param name="words"></param>
        /// <param name="color"></param>
        public void SetColorWords(string []words, System.Drawing.Color color)
        {
            for (int i = 0; i < words.Length; i++)
            {
                string word = words[i];
                while (true)
                {
                    int findIndex = 0;

                    findIndex = NextFind(word);

                    //검색된 것이 없다면
                    if (findIndex == -1)
                        break;

                    int result = this.Find(word, findIndex, findIndex + word.Length, RichTextBoxFinds.MatchCase);
                    if (result == -1)
                        break;

                    this.SelectionColor = color;
                    this.DeselectAll();
                    this.SelectionColor = System.Drawing.Color.Black;
                }
                this.seekIndex = 0;
            }
            this.SelectionLength = 0;
        }
        #endregion
        /// <summary>
        /// seekIndex부터 word에 해당하는 시작되는 Index 반환
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private int NextFind(string word)
        {
            int i = 0;
            for (i = seekIndex; i < this.Text.Length; i++)
            {
                int wordIndex = 0;
                while (true)
                {
                    if (this.Text[i] == word[wordIndex])
                    {
                        i++;
                        wordIndex++;
                        if (wordIndex == word.Length)
                        {
                            this.seekIndex = i;
                            return i - word.Length;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            this.seekIndex = i;
            return -1;
        }

 

 

결과 화면

 

 

 

 

 

TestRichTextBox.zip

 

 

'.Net > Winform' 카테고리의 다른 글

C# Keyboard, Mouse Hooking  (0) 2012.06.28
C# 지정한 폴더 감시하기  (0) 2012.06.27
RichTextBox Keyword 비쥬얼 스튜디오 효과내기  (0) 2012.05.10
C# WndProc이용, USB인식 및 해제 감시  (0) 2011.12.07
C# FileSystemWatcher  (3) 2011.12.07

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace WebSolus.Windows.Controls
{
    class KeyWordRichTextBox:RichTextBox
    {
        #region 속성
        /// <summary>
        /// 검색할 KeyWord를 가져오거나 설정합니다.
        /// </summary>
        public List<string> KeyWords {get;set; }
        #endregion

        #region 생성자
        /// <summary>
        /// 생성자
        /// </summary>
        public KeyWordRichTextBox()
        {
            InitializeComponent();
        }
        #endregion

        #region InitializeComponent
        /// <summary>
        /// InitializeComponent
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.ResumeLayout(false);
            this.KeyWords = new List<string>();
            this.KeyUp += new KeyEventHandler(KeyWordRichTextBox_KeyUp);
        }
        #endregion

        #region Api Function
        /// <summary>
        /// Caret의 위치를 가져옵니다.
        /// </summary>
        /// <param name="pt">Point 개체</param>
        /// <returns>true 성공,false 실패</returns>
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern bool GetCaretPos(out System.Drawing.Point pt);
        #endregion

        #region Event
        /// <summary>
        /// 키를 놓을 때 발생합니다.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void KeyWordRichTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            for (int i = 0; i < this.KeyWords.Count; i++)
            {
                string word = this.KeyWords[i];
                if (this.SelectionStart >= word.Length)
                {
                    int result = this.Find(word, this.SelectionStart - word.Length, this.SelectionStart, RichTextBoxFinds.MatchCase);
                    if (result != -1)
                    {
                        System.Drawing.Point nearPoint = new System.Drawing.Point();
                        GetCaretPos(out nearPoint);
                        int index = this.GetCharIndexFromPosition(nearPoint);
                        this.SelectionColor = System.Drawing.Color.Blue;
                        if (index + 1 == this.TextLength)
                        {
                            this.SelectionStart = index + 1;
                        }
                        else
                        {
                            this.SelectionStart = index;
                        }
                        this.SelectionColor = System.Drawing.Color.Black;
                        this.DeselectAll();

                    }

                }
            }
        }
        #endregion
    }
}

 

 

 

결과 이미지

 

 

 

 

 

프레임워크 버젼 : 닷넷 프레임워크 2.0

 

 

TestRichTextBox.zip

'.Net > Winform' 카테고리의 다른 글

C# Keyboard, Mouse Hooking  (0) 2012.06.28
C# 지정한 폴더 감시하기  (0) 2012.06.27
RichTextBox 원하는 단어들 원하는 색으로 변경  (0) 2012.05.11
C# WndProc이용, USB인식 및 해제 감시  (0) 2011.12.07
C# FileSystemWatcher  (3) 2011.12.07

 

protected override void WndProc(ref Message m)

{

      UInt32 WM_DEVICECHANGE = 0x0219;

      UInt32 DBT_DEVTUP_VOLUME = 0x02;

      UInt32 DBT_DEVICEARRIVAL = 0x8000;

      UInt32 DBT_DEVICEREMOVECOMPLETE = 0x8004;

if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEARRIVAL)) //디바이스 연결

{

      int devType = Marshal.ReadInt32(m.LParam, 4);

      if (devType == DBT_DEVTUP_VOLUME)

      {

            RefreshDevice();

      }

}

if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)) //디바이스 연결 해제

{

      int devType = Marshal.ReadInt32(m.LParam, 4);

      if (devType == DBT_DEVTUP_VOLUME)

      {

            RefreshDevice();

      }

}

 

base.WndProc(ref m);

}

 

 

 

public void RefreshDevice()

{

            listBox1.Items.Clear();

            string[] ls_drivers = System.IO.Directory.GetLogicalDrives(); //연결 되어있는 디바이스 얻어오기

            foreach (string device in ls_drivers)

            {

            System.IO.DriveInfo dr = new System.IO.DriveInfo(device);

            if (dr.DriveType == System.IO.DriveType.Removable) //제거 가능한 타입이라면

            {

                  listBox1.Items.Add(device);

            }

      }

}

 

FileSystemWatcher

작성자 : 김동영

작성일 : 2011. 12. 7

제목 : C# 폴더 감시

 

FileSystemWatcher 클래스는 파일 시스템 변경 알림을 수신하면서 디렉토리 또는

디렉토리의 파일이 변경되면 이벤트를 발생시킵니다.

 

FileSystemWatcher fs = new FileSystemWatcher();//개체 생성

fs.Path = "Test"; //Test 폴더 감시

fs.NotifyFilter = NotifyFilters.FileName|NotifyFilters.DirectoryName; //파일 이름과 폴더 이름 감시

fs.Filter = ""; //특정 파일 감시 ex)*.exe,(모두 감시"", *.*)

fs.Created += new FileSystemEventHandler(fs_Created); //조건에 해당하는 파일 및 폴더의 생성 이벤트 등록

fs.Deleted+=new FileSystemEventHandler(fs_Deleted); //조건에 해당하는 파일 및 폴더의 삭제 이벤트 등록

fs.EnableRaisingEvents = true; //이벤트 활성화

 

testeventhandler += new mydele(Form1_testeventhandler);

 

 

속성

설명

Path

조사할폴더의경로를가져오거나설정

NotifyFilter

조사할변경내용형식을가져오거나설정

Filter

폴더에서 모니터닝할 파일을 결정하는데 사용되는 필터 문자열을 가져오거나 설정

EnableRaisingEvents

구성 요소가 활성화 되는지 여부를 나타내는 값을 가져오거나 설정

 

 

public partial class Form1 : Form

{

delegate void mydele(string path);

event mydele testeventhandler;

 

public Form1()

{

InitializeComponent();

InitWatcher();

}

 

private void InitWatcher()

{

FileSystemWatcher fs = new FileSystemWatcher();

fs.Path = "Test";//

fs.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;

fs.Filter = "";

fs.Created += new FileSystemEventHandler(fs_Created);

fs.Deleted += new FileSystemEventHandler(fs_Deleted);

fs.EnableRaisingEvents = true;

 

testeventhandler += new mydele(Form1_testeventhandler);

}

 

void fs_Deleted(object sender, FileSystemEventArgs e)

{

MakeMessage(e.FullPath, "삭íe제|");

}

 

void Form1_testeventhandler(string path)

{

listBox1.Items.Add(path);

}

 

 

 

void fs_Created(object sender, FileSystemEventArgs e)

{

MakeMessage(e.FullPath,"생성");

}

 

private void MakeMessage(string FullPath, string msg)

{

string path = string.Format("{0}\\{1}", Application.StartupPath, FullPath);

string extension = Path.GetExtension(path); //확장자 검사 폴더면 Null 반환

if (extension == string.Empty)

{

path = string.Format("{0} 폴더가 {1}되었습니다", path, msg);

}

else

{

path = string.Format("{0} 파일이 {1}되었습니다", path, msg);

}

listBox1.Invoke(testeventhandler, new object[] { path });

}

}

 

    

결과:

 

 

 

 

자세한 내용: MSDN 링크

+ Recent posts