일단 부모창의 IsMdiContainer의 속성을 true로 변경해준다.

 

this.IsMdiContainer = true;

 

 

 

자식창을 생성 할 때 자식창의 MdiParent 속성에 부모 Form을 넣어준다.

  

                                                                                   Form form = new Form();
                                                                                   form.MdiParent = this;
                                                                                   form.Show();

 

 

 

MDI 정렬 시키는 방법은 부모의 LayoutMdi 메서드를 호출하면 된다.

 

this.LayoutMdi(MdiLayout.TileHorizontal);

 

 

 

 

 

멤버 이름

설명

Cascade

모든 MDI 자식 창은 MDI 부모 폼의 클라이언트 영역 내에서 계단식으로 배열됩니다.

TileHorizontal

모든 MDI 자식 창은 MDI 부모 폼의 클라이언트 영역 내에서 가로 바둑판식으로 배열됩니다.

TileVertical

모든 MDI 자식 창은 MDI 부모 폼의 클라이언트 영역 내에서 세로 바둑판식으로 배열됩니다.

ArrangeIcons

모든 MDI 자식 아이콘은 MDI 부모 폼의 클라이언트 영역 내에 정렬됩니다.

(표 1)MdiLayout Enum

*출처 : MSDN

void Document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) 
{ 
   int itar=0; 
   foreach (char c in this.richTextBox.Text) 
   { 
      if (c != '\n') 
      { 
         this.richTextBox.Select(itar, 1); 
         Point point = this.richTextBox.GetPositionFromCharIndex(itar); 
         e.Graphics.DrawString(c.ToString(), this.richTextBox.SelectionFont, new SolidBrush(this.richTextBox.SelectionColor), point); 
      } 
      itar++; 
   } 
}  

 

 

 

 

    public partial class TestCheckBoxInGridView : Form
    {
        public TestCheckBoxInGridView()
        {
            InitializeComponent();
        }

        private void TestCheckBoxInGridView_Load(object sender, EventArgs e)
        {
            this.dataGridView.Rows.Add(false, "test1");
            this.dataGridView.Rows.Add(false, "test2");
        }

        private void button_check_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("체크된 항목 : \r\n");
            for(int i=0;i<this.dataGridView.Rows.Count;i++)
            {
                DataGridViewRow dr =  this.dataGridView.Rows[i];
                bool state = (bool)dr.Cells[0].Value;
                if (state == true)
                {
                    sb.AppendLine(dr.Cells[1].Value.ToString());
                }
            }
            MessageBox.Show(sb.ToString());
        }

        
    }


 

 

 

 

 

    public partial class TransparentPanel : System.Windows.Forms.Panel
    {
        public TransparentPanel()
        {

        }

        public TransparentPanel(IContainer container)
        {
            container.Add(this);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x20;
                return cp;
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e) { }

    }

 

JavaScript의 메서드를 호출 하는 것은 지난번에 포스팅하였다.

http://ehdrn.tistory.com/197

 

이번에는 JavaScript에서 이벤트가 발생하였을 때

CallBack 받는 부분을 작성하려고 한다.

 

 

Class Atttribute 아래의 코드 작성과

[System.Runtime.InteropServices.ComVisibleAttribute(true)]

 


CallBack 받을 메서드 Attribute에 아래의 코드를 작성 해주면된다.

[System.Runtime.InteropServices.DispId(0)]

 

 

C# 호출 부분

인스턴스를 넘겨주어야한다.

 

this.Document.InvokeScript("CreateSimpleTextMarker", new object[] { marker.LatLng.Lat, marker.LatLng.Lng, marker.Content, cssText, marker.MarkerDrawEvent });


 

 

 

C# Class

 

    /// <summary>
    /// Marker의 Draw Event를 받기 위한 Class
    /// </summary>
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public class MarkerDrawEvent
    {
        /// <summary>
        /// Marker Draw Delegate
        /// </summary>
        /// <param name="point"></param>
        public delegate void MarkerDrawEventHandler(Point point);

        /// <summary>
        /// Marker Click EventHandler
        /// </summary>
        public event MarkerDrawEventHandler MarkerDraw;


        /// <summary>
        /// 자바스크립트 코드에서 CallBack 받기위한 메서드
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        
        [System.Runtime.InteropServices.DispId(0)]
        public void MarkerDrawRaised(string _point)
        {
            string []xy = _point.Split(new char[] { ',','(',')' }, StringSplitOptions.RemoveEmptyEntries);
            string x = xy[0];
            string y = xy[1];
            if (MarkerDraw != null)
            {
                MarkerDraw(new Point(Convert.ToInt32(x),Convert.ToInt32(y)));
            }
        }
    }


 

JavaScript

    //간단한 텍스트 마커를 생성합니다.
    function CreateSimpleTextMarker( lat, lng, content, cssText, markerDrawEventHandler) {

 

......생략.....

 

SimpleTextMarker.prototype.draw = function () { var projection = this.getProjection(); self.m_projection = projection; var point = projection.pointFromCoords(this.position_); var width = this.node_.offsetWidth; var height = this.node_.offsetHeight; this.node_.style.cssText = cssText + 'position: absolute; white-space: nowrap; left: ' + (point.x - width / 2) + 'px; top: ' + (point.y - height / 2) + 'px'; if (markerDrawEventHandler != null) { markerDrawEventHandler(point.toString()); } }; ......생략.....

 

}


 

 

WebBrowser 컨트롤의 Document 개체를 이용해서

JavaScript의 GetPoint function을 호출하고 문자열을 리턴받기

 

 

C#

string value = (string)this.Document.InvokeScript("GetPoint", new object[] { latLng.Lat, latLng.Lng }).ToString();


 

 

JavaScript

    //해당 위도경도에 해당하는 Point를 가져온다.
    function GetPoint(lat, lng) {
        var point = m_projection.pointFromCoords(new daum.maps.LatLng(lat, lng));
        return point.toString();
    }


 

WebBrowser 컨트롤을 이용하여 윈폼에서

Daum Map API를 사용하는 예제입니다.

 

웹이 아닌 CS상에서 구현하기 위하여

테스트 중에 있습니다.

 

다음의 지도 API 시작하기의 Hello World를 따라하였습니다.

http://dna.daum.net/apis/maps/intro#toc-hello-world

 

아래의 소스와 같습니다.

 

 Test를 위해

Debug파일에 daumMapAPI.html 이름으로 작성하였습니다.

<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<meta name="viewport" content="initial-scale=1.0,user-scalable=no">
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { width: 100%; height: 100% }
</style>
<script type="text/javascript" src="http://apis.daum.net/maps/maps3.js?apikey=APIKEY를 넣어주세요"></script>
<script type="text/javascript">
 window.onload = function() {
 var position = new daum.maps.LatLng(37.537123, 127.005523);

 var map = new daum.maps.Map(document.getElementById('map'), {
  center: position,
  level: 4,
  mapTypeId: daum.maps.MapTypeId.HYBRID
 });

 var marker = new daum.maps.Marker({
  position: position
 });
 marker.setMap(map);

 var infowindow = new daum.maps.InfoWindow({
  content: 'Hello, World!'
 });
 infowindow.open(map, marker);
 };
</script>
</head>
<body>
<div id="map"></div>
</body>
</html> 

 

 

 

cs상에서 간단하게

WebBrowser 개체의 Navigate 메서드를 호출해주시면 됩니다.

 

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                string url = Environment.CurrentDirectory + "\\daumMapAPI.html";
                this.webBrowser.Navigate(url);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


 

 

 

[ 이미지 1] 결과화면

 

 

 

아고...웹을 하나도 몰라 몇시간 삽질했네요.....ㅡㅜ

웹 공부도 해야하는데 흑흑...

 

다음 글에서는 CS에서 자바스크립트

호출하는 부분에 대해 작성할 것 같습니다~

목 차

 

 

  • MS Chart 란

     

  • MS Chart 설치 및 예제

 

 

 

 

 

  • MS Chart 란

MS에서 제공하는 무료 WinForm / ASP.NET 차트입니다.

아래와 같은 차트를 아주 쉽게 MS Chart를 이용해 사용 하실 수 있습니다.

 

 

 

 

==============================================================

 

  • MS Chart 설치 및 예제

 

차트 컨트롤을 비쥬얼 스튜디오 2008과 통합 :

Microsoft Chart Controls Add-on for Microsoft Visual Studio 2008

 

컨트롤과 차트 컨트롤 설치하시고, 비쥬얼 스튜디오 2008과 통합 시켜주는 AddOn을 다운받아 설치 하시면 됩니다. 설치 중 특별한 것은 없으므로 넘어 가도록 하겠습니다.

 

도구 상자 항목 선택으로 가서 Chart 2개 모두 체크하고 확인 버튼을 누릅니다.

 

 

도구 상자에 Chart 컨트롤을 확인 하실 수 있습니다. 드래그 하여 Form으로 옮깁니다.

 

 

 

속성을 중 Annotations는 차트 주석 컬렉션이고, ChartAreas는 차트 영역으로 여러 개의 차트를 설정 할 수 있고, Legends는 차트 범례입니다. Series는 차트 계열로써 차트 타입을 선택 할 수 있습니다. Titles는 차트 제목입니다.

 

 

 

Series의 속성 ChartType으로 차트 타입을 추가 하실 수 있습니다.

비하인드 코드로 파이를 설정 하는 예제를 보겠습니다.

 

 

 

 

 

==============================================================

 

 

아래의 이미지는 예제의 결과 입니다.

Series 3개를 생성하여 각각 Bubble, Range, Spline 타입으로 설정하였습니다.

 

 

 

 

namespace AboutChart

{

public partial class Form1 : Form

{

Series weight_series = new Series();

Series height_series = new Series();

Series fat_series = new Series();

 

public Form1()

{

InitializeComponent();

 

}

필드에서는 체중,키,비만의 Series 개체를 생성합니다.

 

 

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)

{

if (e.Index == 0)

{

if (e.CurrentValue == CheckState.Checked)

{

chart1.Series.Remove(fat_series);

}

else

{

MakeFatStatisticsChart();

}

}

else if (e.Index == 1)

{

if (e.CurrentValue == CheckState.Checked)

{

chart1.Series.Remove(weight_series);

}

else

{

MakeWeightStatisticsChart();

}

}

else if (e.Index == 2)

{

if (e.CurrentValue == CheckState.Checked)

{

chart1.Series.Remove(height_series);

}

else

{

MakeHeightStatisticsChart();

}

}

 

}

체크 리스트 박스에서 체크 박스를 선택하게 변하게 되면 이벤트가 발생하게 하였습니다.

체크가 안되어 있을 때 선택 하였을 때는, 화면에 해당 차트를 보여주고, 체크가 되어 있을 때 선택 하였을 때는 해당 차트를 제거합니다.

 

 

private void MakeFatStatisticsChart()

{

fat_series.Points.Clear();

 

fat_series.Name = "자기 비만도";

fat_series.ChartArea = "ChartArea1";

fat_series.ChartType = SeriesChartType.Bubble;

fat_series.Legend = "Legend1";

 

chart1.Series.Add(fat_series);

 

Push_data(fat_series, "2010.11.1", 50);

Push_data(fat_series, "2010.11.2", 30);

Push_data(fat_series, "2010.11.3", 40);

Push_data(fat_series, "2010.11.4", 10);

 

}

Series클래스의 Points는 차트의 X, Y축의 값입니다.

Name은 차트 오른쪽 상단에 이름이며, ChartArea는 생성한 ChartArea 이름 입니다.

ChartType은 Bubble로 설정해 주었습니다.

Chart에 Series를 추가해주고, Push_data 메소드를 통해 fat_series Series에 x, y축의 데이터를 추가하게 됩니다.

 

private void Push_data(Series series, string p, int p_3)

{

DataPoint dp = new DataPoint();

dp.SetValueXY(p, p_3);

series.Points.Add(dp);

}

 

 

 

private void MakeWeightStatisticsChart()

{

weight_series.Points.Clear();

 

weight_series.Name = "체중 변화도";

weight_series.ChartArea = "ChartArea1";

 

weight_series.ChartType = SeriesChartType.Range;

weight_series.Legend = "Legend1";

 

chart1.Series.Add(weight_series);

 

Push_data(weight_series, "2010.11.1", 30);

Push_data(weight_series, "2010.11.2", 40);

Push_data(weight_series, "2010.11.3", 10);

Push_data(weight_series, "2010.11.4", 20);

}

 

private void MakeHeightStatisticsChart()

{

height_series.Points.Clear();

 

height_series.Name = "키 변화도";

height_series.ChartArea = "ChartArea1";

height_series.ChartType = SeriesChartType.Spline;

height_series.Legend = "Legend1";

 

chart1.Series.Add(height_series);

 

Push_data(height_series, "2010.11.1", 10);

Push_data(height_series, "2010.11.2", 30);

Push_data(height_series, "2010.11.3", 50);

Push_data(height_series, "2010.11.4", 20);

}

키와 체중도 ChartType을 제외하곤 같습니다.

 

 

==============================================================

 

 

 

 

DataPoint dp = new DataPoint();

dp.SetValueY(textBox2.Text);

series1.Points.Add(dp);

X축의 데이터를 추가하지 않으시면, 아래의 그림과 같이포인트를 추가 할 수록 X값이 1부터 시작하여 자동적으로 늘어 나는 것을 확인 하실 수 있습니다.

 

 

제목은 거창하나.....하하...지식인 답변달기 위해 작성한 프로젝트입니다.

사용자가 폴더 경로를 선택하면 해당 폴더의 하위 폴더들과 파일들의 아이콘들을 가져와서

ListView에 추가하는 로직입니다.

더불어 아이콘을 더블 클릭하면 폴더 및 파일이 실행됩니다.

 

결과 화면부터 보겠습니다.

 

[이미지 1] 결과화면

 

 

 

Icon은

http://bbangwon.tistory.com/20

위의 블로그에서 Icon 얻어오는 소스 사용하였습니다.

 

 

프로젝트 설명하겠습니다.

디자이너는 아래의 이미지와 같이 구성하였습니다.

 

 

[이미지 2] 디자이너 화면

 

 

 

 

소스입니다. 이거 원 전체 소스를 올려버렸네요..ㅡㅡ;

흠...주석 달기가 애매해서 일단 올립니다.

문의 사항은 ehdrnsep@nate.com 메일주세요!

 

HowToImageListView.zip

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace HowToImageListView
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 현재 폴더 경로입니다.
        /// </summary>
        string selectedFolderPath;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //ListView의 표시방법을 LrageIcon으로 설정
            this.listView.View = View.LargeIcon;
            this.listView.MouseDoubleClick += new MouseEventHandler(listView_MouseDoubleClick);
        }


        /// <summary>
        /// ListView에서 Mouse DoubleClick 하였을 때
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void listView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.listView.SelectedItems.Count != 0)
            {
                string path = this.listView.SelectedItems[0].Text;

                //폴더라면
                if (System.IO.Directory.Exists(path) == true)
                {
                    System.Diagnostics.Process.Start(path);
                }
                else //파일이라면
                {
                    System.Diagnostics.Process.Start(string.Format(@"{0}\{1}",this.selectedFolderPath,path));
                }
            }
        }

        /// <summary>
        /// 폴더 경로 설정
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem_Open_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fb = new FolderBrowserDialog();
            if (fb.ShowDialog() == DialogResult.OK)
            {
                this.selectedFolderPath = fb.SelectedPath;
                AddListViewLargeImageItem(fb.SelectedPath);
            }
        }

        /// <summary>
        /// 해당 폴더 경로의 아이콘들을 ListView에 추가한다.
        /// </summary>
        /// <param name="p"></param>
        private void AddListViewLargeImageItem(string folderPath)
        {
            this.listView.Items.Clear();

            ImageList imageList = new ImageList();
            imageList.ImageSize = new Size(32, 32);

            AddFolderIcon(ref imageList, folderPath);
            AddFileIcon(ref imageList, folderPath);
            
            this.listView.LargeImageList = imageList;
        }


        /// <summary>
        /// 파일의 아이콘을 추가합니다.
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="folderPath"></param>
        private void AddFileIcon(ref ImageList imageList, string folderPath)
        {
            string[] files = System.IO.Directory.GetFiles(folderPath);
            foreach (string file in files)
            {
                //아이콘 추가
                Icon icon = Etier.IconHelper.IconReader.GetFileIcon(file, Etier.IconHelper.IconReader.IconSize.Large, false);
                imageList.Images.Add(icon);

                this.listView.Items.Add(System.IO.Path.GetFileName(file), imageList.Images.Count - 1);
            }
        }

        /// <summary>
        /// 폴더의 아이콘을 추가합니다.
        /// </summary>
        /// <param name="imageList"></param>
        /// <param name="folderPath"></param>
        private void AddFolderIcon(ref ImageList imageList, string folderPath)
        {
            string[] folders = System.IO.Directory.GetDirectories(folderPath);

            foreach (string folder in folders)
            {
                //아이콘 추가
                Icon icon = Etier.IconHelper.IconReader.GetFolderIcon(Etier.IconHelper.IconReader.IconSize.Large, Etier.IconHelper.IconReader.FolderType.Open);
                imageList.Images.Add(icon);

                this.listView.Items.Add(System.IO.Path.GetDirectoryName(folder), imageList.Images.Count - 1);
            }
        }

        
    }
}


 

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

C# Winform에서 DaumAPI 사용하기[1]_WebBrowser Control 사용  (0) 2012.09.10
C# MS Chart  (2) 2012.08.30
C# 자신의 IP 및 MAC ADRESS 확인하기  (0) 2012.08.29
C# Ping 확인  (0) 2012.08.28
C# 계정을 이용한 Directory Lock & Unlock  (0) 2012.08.28

+ Recent posts