[C# / VisualStudio] C#에서 Naver의 SmartEditor 사용 - 1.컨트롤 작업

2023. 7. 27. 21:23C#/공부

c#에서 이 작업이 필요한가싶지만, 나는 실제로 필요로 인해 작업한 부분이기 때문에 기록해둔다.

 

 

화면은 총 2개가 필요하다. (WinForm)

1. na_list : 게시글 list (더블클릭시 게시글을 볼 수 있고, 작성버튼을 통해 게시글 작성 가능)

2. na_Form : 컨트롤을 띄워서 게시글을 작성하거나 볼 수 있다.

 

컨트롤은 1개. (사용자 정의 컨트롤)

1. na_control : smartEditor를 직접적으로 띄우는 컨트롤이다.

 

 

 

나는 무료 sql인 오라클을 사용했지만 충분히 다른 sql과 함께 사용가능하다.

오라클을 연결해서 데이터를 다루는 내용은 다른 게시글에 작성하도록 하겠다.

 

 

 

작업을 시작해보자.

 

1. html과 js로 smartEditor를 웹페이지로 작업. 웹에서 smartEditor가 정상적으로 작동해야한다.

 

2. smartEditor의 html과 js등이 들어있는 폴더를 c# 프로젝트의 아래 경로로 이동시킨다.

TextEditor_na_sm\TextEditor_na_sm\bin\Debug\

 

(내 프로젝트의 이름은 TextEditor_na_sm이다.)

 

3. 프로젝트에 사용자정의 컨트롤을 만들어준다.

 

4. 도구상자에 있는 webBrowser를 생성한 후, webBrowser의 DocumentCompleted 함수를 생성.

 

5.코딩

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace TextEditor_na_sm
{
    public partial class na_control : UserControl
    {
        string num = ""; //게시글 VIEW시 받아올 게시글 NUMBER

        public na_control()
        {
            InitializeComponent();
        }

        public void CreateEditor() //게시글 Write
        {
            webBrowser1.ScriptErrorsSuppressed = true; //오류메세지 띄우기 여부

            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"smartEditor\index.html"))) //파일이 존재하는지
            {
                //파일을 띄워주기
                webBrowser1.Url = new Uri(@"file:///" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"smartEditor\index.html").Replace('\\', '/'));
            }
            else
            {
                MessageBox.Show("smartEditor 생성 오류", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void CreateEditor_bind(string num)// 게시글 view
        {
            webBrowser1.ScriptErrorsSuppressed = true;

            if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"smartEditor\view.html"))) //파일이 존재하는지 체크
            {
                webBrowser1.Url = new Uri(@"file:///" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"smartEditor\view.html").Replace('\\', '/')); //경로 가져오기
            }
            else
            {
                MessageBox.Show("smartEditor 생성 오류", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            
            this.num = num;//view시 받아온 number 설정
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Bind();// 꼭 이렇게 해줘야함.
        }

        public void Bind()//게시글을 보는 작업
        {
            C_na na = new C_na(); //db작업하는 부분이다. 자신이 사용하는 방법으로 데이터를 가져오면 된다.

            using (DataSet result = na.VIEW(num))
            {
            	//webBrowser에 띄운 html에 있는 "content"라는 이름의 Id를 가져온다. 난 <div><span id="content"></span></div> << 이렇게 줬다.
                HtmlElement textArea = webBrowser1.Document.GetElementById("content");
                if (textArea != null)
                {
                    textArea.InnerHtml = result.Tables[0].Rows[0]["cont"].ToString().Trim();
                }
            }
        }

        public void Save_btn(string title)//작성한 내용을 저장하는 작업
        {
            C_na na = new C_na();
            try
            {
            	//smartEditor 사용시 저장을 위해서는 코드 한줄이 필요하다. 난 html안의 <script> 부분에 fn_save라는 함수를 만들어 여기서 실행시켜줬다.
                webBrowser1.Document.InvokeScript("fn_save");

				//<textarea id="txtContent"></textarea>
                HtmlElement textArea = webBrowser1.Document.GetElementById("txtContent"); //htmlElemet가져오기. //id를 통해서 가져옴.
                string content = textArea.GetAttribute("value"); //value속성 값 가져오기.

                na.INSERT(title, content); //db에 insert
            }
            catch (Exception e)
            {
                MessageBox.Show("error");
            }
        }


    }
}
//index.html(작성 폼) 의 script 부분
<script>
	function fn_save(){
        oEditors.getById["txtContent"].exec("UPDATE_CONTENTS_FIELD", []);
    }
</script>

 

 

사실 이 부분이 제일 중요하다.

 

나머지 winForm부분은 다음에 이어서 작성하겠다.