[XtraGrid] Copy & Paste 구현

.Net/XtraGrid 2012. 4. 11. 14:06

링크 : http://www.devexpress.com/Support/Center/p/A1266.aspx 

Copy 구현 : http://www.devexpress.com/Support/Center/p/A332.aspx

셀렉션 옵션 : http://documentation.devexpress.com/#WindowsForms/CustomDocument711  



using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils.Drawing;


namespace KIS.DevExpressHelper
{
    public class GridLClipboardHelper
    {
        private const string CellDelimiter = "\t";
        private const string LineDelimiter = "\r\n";
        protected GridView _view;

        /// 생성자
        public GridLClipboardHelper(GridView view)
        {
            this.View = view;
        }
        public GridView View
        {
            get { return _view; }
            set
            {
                if ( _view != value )
                {
                    Detach();
                    Attach(value);
                }
            }
        }

        protected virtual void Attach(GridView view)
        {
            if ( view == null )
                return;
            this._view = view;

            if ( view.IsMultiSelect == false )
            {
                view.OptionsSelection.MultiSelect       = true;
                view.OptionsSelection.MultiSelectMode   = GridMultiSelectMode.RowSelect;
            }

            this.View.KeyDown       += new KeyEventHandler(View_KeyDown);
        }

        private bool CompareGrid(GridView srcView, GridView tgtView)
        {
            int srcCnt = srcView.Columns.Count;
            int tgtCnt = tgtView.Columns.Count;

            if ( srcView == null || tgtView == null )
            {
                return false;
            }

            if ( srcCnt != tgtCnt )
            {
                return false;
            }

            for ( int i = 0; i < srcCnt; i++ )
            {
                if ( srcView.Columns[i].ColumnType != tgtView.Columns[i].ColumnType 
                     || srcView.Columns[i].FieldName != tgtView.Columns[i].FieldName
                    )
                {
                    return false;
                }
            }

            return true;
        }

        void View_KeyDown(object sender, KeyEventArgs e)
        {
            GridView view = sender as GridView;

            // 붙여 넣기
            if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.V )
            {
                this.Paste(view);
            }
            // 복사하기
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.C )
            {
                e.SuppressKeyPress = true;
                this.Copy(view);
            }
            // 모두 선택
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.A )
            {
                this.SelectAll(view);
            }
            // 삭제
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true &&  e.KeyCode == Keys.Delete )
            {
                this.DeleteRows(view);
            }
            // 오려내기
            else if ( this.CompareGrid(this._view, view) == true && view.IsMultiSelect == true && e.Control == true && e.KeyCode == Keys.X )
            {
                this.Copy(view);
                this.DeleteRows(view);
            }
        }

        /// 모두 선택
        public void SelectAll(GridView view)
        {
            view.SelectAll();
        }

        // 복사하기
        public void Copy(GridView view)
        {
            StringBuilder sb = new StringBuilder();
            int columnNameCnt = view.Columns.Count;
            for ( int i = 0; i < columnNameCnt; i++ )
            {
                try
                {
                    sb.Append(view.Columns[i].FieldName.ToString());
                }
                catch ( ArgumentException )
                {
                    sb.Append("");
                }

                if ( i+1 < columnNameCnt )
                    sb.Append(CellDelimiter);
            }
            sb.Append(LineDelimiter);


            int[] rows = view.GetSelectedRows();
            int rowsCnt = rows.Length;
            for ( int i = 0; i < rowsCnt; i++ )
            {
                int handle = rows[i];
                DataRowView rowView = view.GetRow(handle) as DataRowView;
                if ( rowView != null )
                {
                    for ( int j = 0; j < columnNameCnt; j++ )
                    {
                        try
                        {
                            sb.Append(rowView[view.Columns[j].FieldName].ToString());
                        }
                        catch ( ArgumentException )
                        {
                            sb.Append("");
                        }

                        if ( j+1 < columnNameCnt )
                            sb.Append(CellDelimiter);
                    }
                }
                if ( i+1 < rowsCnt )
                    sb.Append(LineDelimiter);
            }

            DataObject data = new DataObject();
            data.SetData(DataFormats.Text, sb.ToString());
            Clipboard.Clear();
            Clipboard.SetDataObject(data, true);
        }

        // 붙여넣기
        public void Paste(GridView view)
        {
            IDataObject data = Clipboard.GetDataObject();
            if ( data.GetDataPresent(DataFormats.Text) == true )
            {
                view.BeginUpdate();
                try
                {
                    string strData          = data.GetData(DataFormats.Text) as string;
                    string[] strRows        = strData.Split(new string[] { LineDelimiter }, StringSplitOptions.None);
                    string[] strColumnNames = strRows[0].Split(new string[] { CellDelimiter }, StringSplitOptions.None);

                    List< object > list = new List< object >();
                    int dataCount               = strRows.Length-1; // 헤더 개수 제외
                    int rowHandle               = view.FocusedRowHandle;
                    int targetDeleteRowCount    = view.DataRowCount - rowHandle + 1;

                    if ( rowHandle != GridControl.InvalidRowHandle && rowHandle != GridControl.NewItemRowHandle )
                    {
                        // 붙여 넣기할 Row가 현재 선택된 행부터 밑에 행보다 많다.
                        if ( targetDeleteRowCount > dataCount )
                        {
                            for ( int i = rowHandle + dataCount; i < view.DataRowCount; i++ )
                            {
                                list.Add(view.GetRow(i));
                            }
                        }

                        // 현재 선택된 행부터 끝까지 삭제한다.
                        for ( int i = view.DataRowCount-1; i >= rowHandle; i-- )
                        {
                            view.DeleteRow(i);
                        }
                    }
                    else if ( rowHandle == GridControl.NewItemRowHandle )
                    {
                        view.DeleteRow(rowHandle);
                    }

                    for ( int i = 1; i < strRows.Length; i++ )
                    {
                        view.AddNewRow();
                        int handle = view.FocusedRowHandle;

                        string[] strCells = strRows[i].Split(new string[] { CellDelimiter }, StringSplitOptions.None);
                        int colCnt = strColumnNames.Length;
                        for ( int j = 0; j < colCnt; j++ )
                        {
                            if ( strColumnNames[j].Trim().Equals("") == false && j < strCells.Length )
                            {
                                try
                                {
                                    Type t = view.Columns[j].ColumnType;
                                    object value = null;
                                    if ( t == typeof(int) )
                                    {
                                        if ( strCells[j] != null && strCells[j].ToString().Equals("") == false )
                                        {
                                            try
                                            {
                                                value = Convert.ToInt32(strCells[j]);
                                                if ( value != null )
                                                    view.SetRowCellValue(handle, strColumnNames[j], value);
                                            }
                                            catch ( Exception ex )
                                            {
                                                System.Console.WriteLine(ex.StackTrace);
                                            }
                                        }
                                    }
                                    else if ( t == typeof(DateTime) )
                                    {
                                        if ( strCells[j] != null && strCells[j].ToString().Equals("") == false )
                                        {
                                            try
                                            {
                                                value = Convert.ToDateTime(strCells[j]);
                                                if ( value != null )
                                                    view.SetRowCellValue(handle, strColumnNames[j], value);
                                            }
                                            catch ( Exception ex )
                                            {
                                                System.Console.WriteLine(ex.StackTrace);
                                            }
                                        }
                                    }
                                    else if ( t == typeof(string) )
                                    {
                                        if ( strCells[j] != null )
                                        {
                                            try
                                            {
                                                value = Convert.ToString(strCells[j]);
                                                if ( value != null )
                                                    view.SetRowCellValue(handle, strColumnNames[j], value);
                                            }
                                            catch ( Exception ex )
                                            {
                                                System.Console.WriteLine(ex.StackTrace);
                                            }
                                        }
                                    }
                                }
                                catch ( Exception ex)
                                {
                                    //MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);
                                }
                            }//if ( strColumnNames[j].Trim().Equals("") == false )
                        }//for ( int j = 0; j < colCnt; j++ )
                    }//for ( int i = 1; i < strRows.Length; i++ )

                    DataView dv = view.DataSource as DataView;
                    for ( int i = 0; i < list.Count; i++ )
                    {
                        DataRowView drv = list[i] as DataRowView;
                        if ( drv != null )
                        {
                            DataRowView newDRV = dv.AddNew();
                            newDRV.BeginEdit();
                            try
                            {
                                int columNameCount= drv.Row.Table.Columns.Count;
                                for ( int j = 0; j < columNameCount; j++ )
                                {
                                    string fieldName = drv.Row.Table.Columns[j].ColumnName;
                                    newDRV[fieldName] = drv[fieldName];
                                }
                                newDRV.EndEdit();
                            }
                            catch ( Exception )
                            {
                                newDRV.CancelEdit();
                            }
                        }
                    }
                }
                catch ( Exception ex )
                {
                    MessageBox.Show(ex.StackTrace);
                }
                finally
                {
                    view.EndUpdate();
                }
            }//if ( data.GetDataPresent(DataFormats.Text) == true )
        }


        /// 현재 선택된 로우를 삭제한다.
        private void DeleteRows(GridView view)
        {
            view.BeginUpdate();
            int[] rows = view.GetSelectedRows();
            for ( int i = rows.Length-1; i >= 0 ; i-- )
            {
                view.DeleteRow(rows[i]);
            }
            view.EndUpdate();
        }

        protected virtual void Detach()
        {
            if ( this._view == null )
                return;

            this.View.KeyDown       -= new KeyEventHandler(View_KeyDown);
            _view = null;
        }
    }
}

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

[XtraGrid] XtraGrid Option  (0) 2013.01.24
[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
posted by 뚱2

링크 : http://msdn.microsoft.com/ko-kr/magazine/cc163528.aspx 


프로세스의 메모리 사용 조사 : http://msdn.microsoft.com/ko-kr/library/cc438089(v=vs.71).aspx

posted by 뚱2

링크 : http://msdn.microsoft.com/ko-kr/library/dd465122.aspx 

링크 : http://msdn.microsoft.com/ko-kr/library/018hxwa8.aspx


이렇게도 사용할수 있군요. 간단한 메소드는 델리게이트 선언하지 않고 바로 사용 할 수 있을듯합니다.


응용 : http://www.devpia.co.kr/MAEUL/Contents/Detail.aspx?BoardID=18&MAEULNO=8&no=1723&page=11 


범용 적으로 사용 하게 만든 클래스 사실 제네릭 인자 3개 더 추가밖에 없습니다.


    
public static class ControlExt
    {
        public static void InvokeIfNeeded(this Control control, Action action)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action);
            }
            else
            {
                action();
            }
        }

        public static void InvokeIfNeeded< T >(this Control control, Action< T > action, T arg)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, arg);
            }
            else
            {
                action(arg);
            }
        }

        public static void InvokeIfNeeded< T1 , T2 >(this Control control, Action< T1 , T2 > action, T1 arg1, T2 arg2)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, new object[] {arg1, arg2});
            }
            else
            {
                action(arg1, arg2);
            }
        }

        public static void InvokeIfNeeded< T1, T2, T3 >(this Control control, Action< T1, T2, T3 > action, T1 arg1, T2 arg2, T3 arg3)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, new object[] { arg1, arg2, arg3 });
            }
            else
            {
                action(arg1, arg2, arg3);
            }
        }

        public static void InvokeIfNeeded< T1, T2, T3, T4 >(this Control control, Action< T1, T2, T3, T4 > action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
        {
            if ( control.InvokeRequired )
            {
                control.Invoke(action, new object[] { arg1, arg2, arg3, arg4 });
            }
            else
            {
                action(arg1, arg2, arg3, arg4);
            }
        }
    }

posted by 뚱2

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

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
[XtraGrid] DevExpress XtraGrid  (0) 2012.03.28
posted by 뚱2

[C#] Assembly Version Loading

.Net/C# 2012. 4. 6. 19:35

현재 어셈블리 버전을 읽는 방법 이다.




// AssemblyInfo.cs
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로
// 지정되도록 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.5.*")]
[assembly: AssemblyFileVersion("0.5.*")]

// Test.cs
// 현재 실행 프로그램의 어셈플리를 로딩한다.
string msg = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
MessageBox.Show("Version=" + msg);

참고로 버전은 Major.Minor.Build.Revision 입니다.

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

[C#] DllImportAttribut  멤버  (0) 2013.01.04
[C#] Visual C# 메소드를 비동기로 호출하는 방법  (0) 2012.04.14
[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
posted by 뚱2
사이트에 있는 예제를 약간 수정했다.
엑셀과 비슷하게 Shift + 클릭으로 범위를 클릭할수 있게 변경했다.
 
    public class GridCheckMarksMultiSelectionHelper
    {
        private readonly string             markFieldName = "CheckMarkSelection";
        protected GridView                  _view;
        protected ArrayList                 selection;
        protected GridColumn                column;
        protected RepositoryItemCheckEdit   edit;
        protected const int                 CheckboxIndent = 4;

        /// 
        /// 생성자
        /// 
        public GridCheckMarksMultiSelectionHelper()
        {
            selection = new ArrayList();
        }
        public GridCheckMarksMultiSelectionHelper(GridView view)
            : this()
        {
            this.View = view;
        }
        public GridView View
        {
            get { return _view; }
            set
            {
                if (_view != value)
                {
                    Detach();
                    Attach(value);
                }
            }
        }
        public string MarkFieldName
        {
            get
            {
                return this.markFieldName;
            }
        }

        private bool isMultiSelect = false;
        public bool IsMultiSelect
        {
            get
            {
                return this.isMultiSelect;
            }

            private set
            {
                this.isMultiSelect = value;
            }
        }


        public GridColumn CheckMarkColumn { get { return column; } }
        public int SelectedCount { get { return selection.Count; } }
        public object GetSelectedRow(int index)
        {
            return selection[index];
        }
        public int GetSelectedIndex(object row)
        {
            foreach (object record in selection)
                if ((record as DataRowView).Row == (row as DataRowView).Row)
                    return selection.IndexOf(record);
            return selection.IndexOf(row);
        }
        public void ClearSelection(GridView view)
        {
            selection.Clear();
            Invalidate(view);
        }
        public void SelectAll(GridView view)
        {
            selection.Clear();
            // fast (won't work if the grid is filtered)
            //if(_view.DataSource is ICollection)
            //	selection.AddRange(((ICollection)_view.DataSource));
            //else
            // slow:
            for (int i = 0; i < view.DataRowCount; i++)
                selection.Add(view.GetRow(i));
            Invalidate(view);
        }
        public void SelectGroup(int rowHandle, bool select, GridView view)
        {
            if (IsGroupRowSelected(rowHandle, view) && select) return;
            for (int i = 0; i < view.GetChildRowCount(rowHandle); i++)
            {
                int childRowHandle = view.GetChildRowHandle(rowHandle, i);
                if (view.IsGroupRow(childRowHandle))
                    SelectGroup(childRowHandle, select, view);
                else
                    SelectRow(childRowHandle, select, false, view);
            }
            Invalidate(view);
        }
        void SelectRow(int rowHandle, bool select, bool invalidate, GridView view)
        {
            if (IsRowSelected(rowHandle, view) == select) return;
            object row = view.GetRow(rowHandle);
            if (select)
                selection.Add(row);
            else
                selection.Remove(row);
            if (invalidate)
            {
                Invalidate(view);
            }
        }
        void SelectRow(object row, bool select, bool invalidate, GridView view)
        {
            if (IsRowSelected(row, view) == select) return;
            if (select)
                selection.Add(row);
            else
                selection.Remove(row);
            if (invalidate)
            {
                Invalidate(view);
            }
        }
        public void SelectRow(int rowHandle, bool select, GridView view)
        {
            SelectRow(rowHandle, select, true, view);
        }
        public void SelectRow(object row, bool select, GridView view)
        {
            SelectRow(row, select, true, view);
        }
        public void InvertRowSelection(int rowHandle, GridView view)
        {
            if (view.IsDataRow(rowHandle))
            {
                SelectRow(rowHandle, !IsRowSelected(rowHandle, view), view);
            }
            if (view.IsGroupRow(rowHandle))
            {
                SelectGroup(rowHandle, !IsGroupRowSelected(rowHandle, view), view);
            }
        }
        public bool IsGroupRowSelected(int rowHandle, GridView view)
        {
            for (int i = 0; i < view.GetChildRowCount(rowHandle); i++)
            {
                int row = _view.GetChildRowHandle(rowHandle, i);
                if (view.IsGroupRow(row))
                {
                    if (!IsGroupRowSelected(row, view)) return false;
                }
                else
                    if (!IsRowSelected(row, view)) return false;
            }
            return true;
        }
        public bool IsRowSelected(int rowHandle, GridView view)
        {
            if (view.IsGroupRow(rowHandle))
                return IsGroupRowSelected(rowHandle, view);

            object row = view.GetRow(rowHandle);

            return GetSelectedIndex(row) != -1;
        }
        public bool IsRowSelected(object row, GridView view)
        {
            return GetSelectedIndex(row) != -1;
        }
        protected virtual void Attach(GridView view)
        {
            if (view == null) return;
            selection.Clear();
            this._view = view;
            edit = view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
            column = view.Columns.Add();
            column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
            column.Visible = true;
            column.VisibleIndex = 0;
            column.FieldName = this.MarkFieldName;
            column.Caption = "Mark";
            column.OptionsColumn.ShowCaption = false;
            column.OptionsColumn.AllowEdit = false;
            column.OptionsColumn.AllowSize = false;
            column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
            column.Width = GetCheckBoxWidth();
            // 2012-04-05 ADDED BY KDJ
            column.Fixed = FixedStyle.Left;
            column.ColumnEdit = edit;

            view.Click                      += new EventHandler(View_Click);
            view.CustomDrawColumnHeader     += new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            view.CustomDrawGroupRow         += new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            view.CustomUnboundColumnData    += new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            view.KeyDown                    += new KeyEventHandler(view_KeyDown);
            view.RowStyle                   += new RowStyleEventHandler(view_RowStyle);

            // 2012-04-05 ADDED BY KDJ
            view.KeyUp                      += new KeyEventHandler(view_KeyUp);
            view.FocusedRowChanged          += new FocusedRowChangedEventHandler(view_FocusedRowChanged);
        }

        void view_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            this._view.BeginUpdate();
            
            // 클릭시 현재 Row 선택되게 하는 루틴
            //bool isSelection = this.IsRowSelected(row, view);
            //this.SelectRow(row, !isSelection, false, view);

            if (this.IsMultiSelect == true)
            {
                int start = 0, end = 0;

                if (e.PrevFocusedRowHandle <= e.FocusedRowHandle)
                {
                    start = e.PrevFocusedRowHandle;
                    end = e.FocusedRowHandle;
                }
                else
                {
                    start = e.FocusedRowHandle;
                    end = e.PrevFocusedRowHandle;
                }

                for (int i = start; i <= end; i++)
                {
                    this.SelectRow(i, true, false, this._view);
                }
                
            }

            this._view.EndUpdate();
        }

        public virtual void DetailViewAttach(GridView view)
        {
            if (view == null) return;
            this._view = view;
            _view.BeginUpdate();
            try
            {
                column = view.Columns[this.MarkFieldName];
                if (column == null)
                {
                    selection.Clear();
                    edit = view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
                    column = view.Columns.Add();
                    column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;
                    column.Visible = true;
                    column.VisibleIndex = 0;
                    column.FieldName = this.MarkFieldName;
                    column.Caption = "Mark";
                    column.OptionsColumn.ShowCaption = false;
                    column.OptionsColumn.AllowEdit = false;
                    column.OptionsColumn.AllowSize = false;
                    column.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
                    column.Width = GetCheckBoxWidth();
                    column.ColumnEdit = edit;
                }
                edit = view.Columns[this.MarkFieldName].ColumnEdit as RepositoryItemCheckEdit;//view.GridControl.RepositoryItems.Add("CheckEdit") as RepositoryItemCheckEdit;
                view.Click                      += new EventHandler(View_Click);
                view.CustomDrawColumnHeader     += new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
                view.CustomDrawGroupRow         += new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
                view.CustomUnboundColumnData    += new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
                view.KeyDown                    += new KeyEventHandler(view_KeyDown);
                view.RowStyle                   += new RowStyleEventHandler(view_RowStyle);

                // 2012-04-05 ADDED BY KDJ
                view.KeyUp                      += new KeyEventHandler(view_KeyUp);
                view.FocusedRowChanged          += new FocusedRowChangedEventHandler(view_FocusedRowChanged);
            }
            finally
            {
                _view.EndUpdate();
            }
        }
        protected virtual void Detach()
        {
            if (_view == null) return;
            if (column != null)
                column.Dispose();
            if (edit != null)
            {
                _view.GridControl.RepositoryItems.Remove(edit);
                edit.Dispose();
            }

            _view.Click                     -= new EventHandler(View_Click);
            _view.CustomDrawColumnHeader    -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            _view.CustomDrawGroupRow        -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            _view.CustomUnboundColumnData   -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            _view.KeyDown                   -= new KeyEventHandler(view_KeyDown);
            _view.RowStyle                  -= new RowStyleEventHandler(view_RowStyle);

            // 2012-04-05 ADDED BY KDJ
            _view.KeyUp                     -= new KeyEventHandler(view_KeyUp);
            _view.FocusedRowChanged         -= new FocusedRowChangedEventHandler(view_FocusedRowChanged);

            _view = null;
        }
        public virtual void DetailViewDetach()
        {
            if (_view == null) return;

            _view.Click                     -= new EventHandler(View_Click);
            _view.CustomDrawColumnHeader    -= new ColumnHeaderCustomDrawEventHandler(View_CustomDrawColumnHeader);
            _view.CustomDrawGroupRow        -= new RowObjectCustomDrawEventHandler(View_CustomDrawGroupRow);
            _view.CustomUnboundColumnData   -= new CustomColumnDataEventHandler(view_CustomUnboundColumnData);
            _view.KeyDown                   -= new KeyEventHandler(view_KeyDown);
            _view.RowStyle                  -= new RowStyleEventHandler(view_RowStyle);

            // 2012-04-05 ADDED BY KDJ
            _view.KeyUp                     -= new KeyEventHandler(view_KeyUp);
            _view.FocusedRowChanged         -= new FocusedRowChangedEventHandler(view_FocusedRowChanged);

            _view = null;
        }
        protected int GetCheckBoxWidth()
        {
            DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            int width = 0;
            GraphicsInfo.Default.AddGraphics(null);
            try
            {
                width = info.CalcBestFit(GraphicsInfo.Default.Graphics).Width;
            }
            finally
            {
                GraphicsInfo.Default.ReleaseGraphics();
            }
            return width + CheckboxIndent * 2;
        }
        protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
        {
            DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
            DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
            DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
            info = edit.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;
            painter = edit.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
            info.EditValue = Checked;
            info.Bounds = r;
            info.CalcViewInfo(g);
            args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
            painter.Draw(args);
            args.Cache.Dispose();
        }
        void Invalidate(GridView view)
        {
            view.CloseEditor();
            view.BeginUpdate();
            view.EndUpdate();
        }
        void view_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.Column.Caption == "Mark")
            {
                if (e.IsGetData)
                    e.Value = /*IsRowSelected((view.DataSource as IList)[e.ListSourceRowIndex],view);*/  IsRowSelected(view.GetRowHandle(e.ListSourceRowIndex), view);
                else
                    SelectRow((view.DataSource as IList)[e.ListSourceRowIndex], (bool)e.Value, view);
            }
        }
        void view_KeyDown(object sender, KeyEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.KeyCode == Keys.ShiftKey && this.isMultiSelect == false)
            {
                this.IsMultiSelect = true;
            }

            if (view.FocusedColumn.Caption != "Mark" || e.KeyCode != Keys.Space) return;
            InvertRowSelection(view.FocusedRowHandle, view);
        }

        void view_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.ShiftKey & this.isMultiSelect == true)
            {
                this.isMultiSelect = false;
            }
        }

        void View_Click(object sender, EventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo info;
            Point pt = view.GridControl.PointToClient(Control.MousePosition);
            Point viewOffset = view.GetViewInfo().Bounds.Location;
            //pt.Offset(-viewOffset.X, -viewOffset.Y);
            info = view.CalcHitInfo(pt);
            if (info.Column != null && info.Column.Caption == "Mark")
            {
                if (info.InColumn)
                {
                    if (SelectedCount == view.DataRowCount)
                        ClearSelection(view);
                    else
                        SelectAll(view);
                }
                if (info.InRowCell)
                {
                    InvertRowSelection(info.RowHandle, view);
                }
            }
            if (info.InRow && view.IsGroupRow(info.RowHandle) && info.HitTest != GridHitTest.RowGroupButton)
            {
                InvertRowSelection(info.RowHandle, view);
            }
        }
        void View_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
        {

            if (e.Column != null && e.Column.Caption == "Mark")
            {
                GridView view = sender as GridView;
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == view.DataRowCount);
                e.Handled = true;
            }
        }
        void View_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
        {
            GridView view = sender as GridView;
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo info;
            info = e.Info as DevExpress.XtraGrid.Views.Grid.ViewInfo.GridGroupRowInfo;

            info.GroupText = "         " + info.GroupText.TrimStart();
            e.Info.Paint.FillRectangle(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
            e.Painter.DrawObject(e.Info);

            Rectangle r = info.ButtonBounds;
            r.Offset(r.Width + CheckboxIndent * 2 - 1, 0);
            DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle, view));
            e.Handled = true;
        }
        void view_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (IsRowSelected(e.RowHandle, view))
            {
                e.Appearance.BackColor = SystemColors.Highlight;
                e.Appearance.ForeColor = SystemColors.HighlightText;
            }
        }
    }


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

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Fixed Columns  (0) 2012.04.05
[XtraGrid] DevExpress XtraGrid  (0) 2012.03.28
posted by 뚱2

[C#] VS 2008 서식 자동 해제

.Net/C# 2012. 4. 6. 10:09

줄 맞춰서 코딩 열심히 하고 Copy & Paste하면은 서식이 자동으로 다시 만들어 진다. ㅡㅡ;

나에게는 참 불편한 기능중에 하나

해제 방법은

'도구 -> 옵션 -> 텍스트 편집기 -> C# -> 서식 -> 일반' 으로 들어가서

모든 서식을 체크 해제한다.



추가 : 이렇게 하니 복사 붙여넣기 할때마다 인던트를 조절해야 하는 불편함이 생긴다.

그럴때는 체크 해주고


선언문의 공백을 무시합니다. 를 체크해준다.



그리고 서식 -> 간격 -> 연산자의 간격을 설정 합니다. -> 이항 연산자 주위의 공백을 무시합니다. 선택

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

[C#] Visual C# 메소드를 비동기로 호출하는 방법  (0) 2012.04.14
[C#] Assembly Version Loading  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
posted by 뚱2

[XtraGrid] Fixed Columns

.Net/XtraGrid 2012. 4. 5. 13:22

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

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] DevExpress XtraGrid  (0) 2012.03.28
posted by 뚱2

[XtraGrid] DevExpress XtraGrid

.Net/XtraGrid 2012. 3. 28. 22:26

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

[XtraGrid] Online Document  (0) 2012.04.13
[XtraGrid] Copy & Paste 구현  (0) 2012.04.11
[XtraGrid] How to make my grid columns read-only  (0) 2012.04.08
[XtraGrid] Checkbox 구현하기  (1) 2012.04.06
[XtraGrid] Fixed Columns  (0) 2012.04.05
posted by 뚱2

[C#] vshosting.exe 가 뭘까요?

.Net/C# 2012. 3. 26. 14:27
WinForm으로 프로그램을 생성하면은 출력 디렉토리에 XXX.vshosting.exe 파일이 생성됩니다.
이게 궁금해서 찾아보니 잘 설명된 블로그가 있어서 링크 걸어둡니다.

링크 : http://blog.naver.com/saltynut?Redirect=Log&logNo=120017351107 

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

[C#] VS 2008 서식 자동 해제  (0) 2012.04.06
[C#] log4net  (0) 2012.04.03
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
[C#] internal 지정자  (0) 2012.03.12
posted by 뚱2
C# ASP.NET 아티클 이지만 윈폼 응용프로그램에서도 유용하게 사용할수 있다.

링크 : http://www.primaryobjects.com/CMS/Article81.aspx 
posted by 뚱2
해당 오프젝트의 타입을 확인하고 메소드가 존재하고 파라미터가 일치한다면
호출해 준다.

// class
public class MyObject
{
    pub int Connect()
    {
        // 접속 ...
    }
    public void GetLastError(out int errorCode, out string errorMessage)
    {
        // 내부 코드들 ...
    }
}


    // ErrorUtil
    public class ErrorUtil
    {
        private static readonly string methodName = "GetLastError";
        private static int errorCode = 0;
        private static string errorMessage = "";

        public static int ErrorCode
        {
            get { return errorCode; }
        }

        public static string ErrorMessage
        {
            get { return errorMessage; }
        }

        public static bool GetLastError(object obj)
        {
            try
            {
                Type t = obj.GetType();
                MethodInfo info = t.GetMethod(
                    ErrorUtil.methodName,
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    new[] 
                    {
                        typeof(int).MakeByRefType(),
                        typeof(string).MakeByRefType()
                    },
                    null
                );

                if (info != null)
                {
                    object[] parameters = new object[2];
                    info.Invoke(obj, parameters);

                    errorCode = (int)parameters[0];
                    errorMessage = (string)parameters[1];
                    return true;
                }
                else
                {
                    errorMessage = String.Format("{0} 메소드를 찾을수 없거나, 파라미터가 정확하지 않습니다.", ErrorUtil.methodName);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return false;
            }
        }
    }


// 사용예
    MyObject oCommpany = new MyObject();
    int retCode = oCompany.Connect();
    if (retCode != 0)
    {
           ErrorUtil.GetLastError(oCompany);
           MessageBox.Show(ErrorUtil.ErrorMessage);
    }


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

[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
[C#] internal 지정자  (0) 2012.03.12
[즐겨찾기] 무료서적 Inside C# 2nd  (0) 2012.03.10
posted by 뚱2

[C#] .Net Control.Invoke

.Net/.Net 2012. 3. 18. 20:17
MFC로만 응용프로그램을 만들어오다 이번에 프로젝트로 C# WinForm으로 응용프로그램을 만들게 되었다.
다른걸 떠나서 생산성 하나는 끝내준다.

각설하고 기본적으로 UI컨트롤은 메세지 루프로 이벤트를 받기때문에 메인 윈도우에서 생성해줘야 한다.
물론 별도 스레드를 만들고 메세지 루프도 만들어주면 가능하기는 한데 이건 된다 이거지 이렇게 사용해본적도
없고 본적도 없다.

백그라운드 작업을 할때 별도의 스레드에서 작업을 하고 메인 스레드에서 프로그레스 바를 이용해서 상태값을
변경해주는 방법을 종종 사용하는데 이게 네이티브 응용프로그램에서는 메세지로 컨트롤 했는데 
.Net쪽에서는 Controls.Invoke를 사용해서 해결한다는걸 삽질끝에 알았다.

Invoke 설명 : http://msdn.microsoft.com/ko-kr/library/system.windows.forms.control.invoke.aspx



위 이미지 같이 각 파일의 복사 나 이동의 상태를 알려주고 아래 프로그래스 바는 전체 파일 단위의 상태를 알려준다.

form code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Threading;

namespace TestExplorer
{
    public partial class FileProgressForm : Form
    {
        public enum ACTION_TYPE {COPY, MOVE}
        delegate void SetProgressValueDelegate(int value);
        delegate void SetLabelTextDelegate(string text);
        delegate void DoEndDelegate();

        private string sourcePath = "";
        private string targetPath = "";
        private byte[] buffer = new byte[1024*100];// 100Kb
        private Thread thread = null;
        private ACTION_TYPE action = ACTION_TYPE.COPY;
        private bool isThreadEnd = false;

        public string SourcePath
        {
            get { return sourcePath;  }
            set { sourcePath = value; }
        }

        public string TargetPath
        {
            get { return targetPath; }
            set { targetPath = value; }
        }

        public ACTION_TYPE Action
        {
            get { return (action); }
            set { action = value;  }
        }

        public FileProgressForm()
        {
            InitializeComponent();
        }

        private void FileProgressForm_Load(object sender, EventArgs e)
        {
        }

        private void DoEnd()
        {
            this.isThreadEnd = true;
            this.DialogResult = DialogResult.OK;
        }

        private void FileProgressForm_Shown(object sender, EventArgs e)
        {
            // 파일 읽기 작업을 시작한다.
            if (File.Exists(this.sourcePath) == false
                && Directory.Exists(this.targetPath) == false)
            {
                MessageBox.Show("원본 폴더나, 파일을 선택해 주세요.");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            if (Directory.Exists(this.targetPath) == false)
            {
                MessageBox.Show("대상 폴더를 선택해 주세요.");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            if (this.sourcePath.Equals(this.targetPath) == true)
            {
                MessageBox.Show("원본과 대상이 일치합니다.");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            thread = new Thread(new ThreadStart(WorkThread));
            thread.Start();
        }

        // 복사 작업을 한다.
        private void WorkThread()
        {
            FileInfo[] arrfileInfo = null;

            if (File.Exists(sourcePath) == true)
            {
                arrfileInfo = new FileInfo[] { new FileInfo(sourcePath) };
            }
            else if (Directory.Exists(sourcePath) == true)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(sourcePath);
                arrfileInfo = dirInfo.GetFiles();
            }

            if (arrfileInfo != null)
            {
                int count = arrfileInfo.Length;
                long total_current = 0;
                long total_total = 0;

                // 총 파일 용량을 가져온다.
                foreach (FileInfo i in arrfileInfo)
                {
                    if ((i.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
                    {
                        total_total += i.Length;
                    }
                }

                // 복사할 파일을 순회한다.
                foreach (FileInfo i in arrfileInfo)
                {
                    if ((i.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    {
                        continue;
                    }

                    FileStream rs = null, ws = null;
                    try
                    {
                        rs = new FileStream(i.FullName, FileMode.Open);
                        ws = new FileStream(targetPath + "\\" + i.Name, FileMode.Create);

                        // 익명 메서드
                        this.Invoke((SetLabelTextDelegate)delegate(string text)
                        {
                            this.label_filename.Text = text;
                        },
                        new object[] {i.Name});


                        int readSize = 0;
                        long current_current = 0;
                        long current_total = i.Length;

                        while ((readSize = rs.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            current_current += readSize;
                            total_current += readSize;
                            // 현재 프로그래스 바
                            int percent = (int)((double)current_current / (double)current_total * 100);

                            Console.WriteLine("cur={0}, total={1}, percent={2}", current_current, current_total, percent);

                            //익명 메서드
                            this.Invoke((SetProgressValueDelegate)delegate(int value)
                            {
                                this.progressCur.Value = value;
                                this.lableCurPercent.Text = String.Format("{0}%", value);
                            },
                            new object[] {percent});

                            // 토탈 프로그래스 바
                            percent = (int)((double)total_current / (double)total_total * 100);
                            
                            //익명 메서드
                            this.Invoke((SetProgressValueDelegate)delegate(int value)
                            {
                                this.progressTotal.Value = value;
                                this.labelTotalPercent.Text = String.Format("{0}%", value);
                            },
                            new object[] { percent });


                            ws.Write(buffer, 0, readSize);
                        }//while ((readSize = rs.Read(buffer, 0, buffer.Length)) != 0)

                        //익명 메서드
                        this.Invoke((SetProgressValueDelegate)delegate(int value)
                        {
                            this.progressCur.Value = value;
                            this.lableCurPercent.Text = String.Format("{0}%", value);
                        },
                        new object[] { 100 });
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        try { rs.Close(); }
                        catch (Exception ex) { }
                        try { ws.Close(); }
                        catch (Exception ex) { }
                    }

                    if (this.action == ACTION_TYPE.MOVE)
                    {
                        File.Delete(i.FullName);
                    }
                }//foreach (FileInfo i in arrfileInfo)

                //익명 메서드
                this.Invoke((SetProgressValueDelegate)delegate(int value)
                {
                    this.progressTotal.Value = value;
                    this.labelTotalPercent.Text = String.Format("{0}%", value);
                },
                new object[] { 100 });

                //TODO: 500 밀리세컨 슬립한다.
                Thread.Sleep(500);
            }//if (arrfileInfo != null)
            this.Invoke((DoEndDelegate)delegate()
            {
                this.DoEnd();
            });
        }//private void WorkThread(object arg)

        private void FileProgressForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (thread != null && thread.IsAlive == true && isThreadEnd == false )
            {
                MessageBox.Show("작업 중입니다.");
                e.Cancel = true;
            }
        }
    }
}


designer code
namespace TestExplorer
{
    partial class FileProgressForm
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            this.progressCur = new System.Windows.Forms.ProgressBar();
            this.progressTotal = new System.Windows.Forms.ProgressBar();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.labelTotalPercent = new System.Windows.Forms.Label();
            this.lableCurPercent = new System.Windows.Forms.Label();
            this.label_filename = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // progressCur
            // 
            this.progressCur.Location = new System.Drawing.Point(13, 49);
            this.progressCur.Name = "progressCur";
            this.progressCur.Size = new System.Drawing.Size(366, 32);
            this.progressCur.Step = 1;
            this.progressCur.TabIndex = 0;
            // 
            // progressTotal
            // 
            this.progressTotal.Location = new System.Drawing.Point(12, 107);
            this.progressTotal.Name = "progressTotal";
            this.progressTotal.Size = new System.Drawing.Size(366, 32);
            this.progressTotal.Step = 1;
            this.progressTotal.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 32);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 2;
            this.label1.Text = "현재 파일 :";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(13, 91);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(65, 12);
            this.label2.TabIndex = 3;
            this.label2.Text = "전체 파일 :";
            // 
            // labelTotalPercent
            // 
            this.labelTotalPercent.AutoSize = true;
            this.labelTotalPercent.Location = new System.Drawing.Point(87, 91);
            this.labelTotalPercent.Name = "labelTotalPercent";
            this.labelTotalPercent.Size = new System.Drawing.Size(21, 12);
            this.labelTotalPercent.TabIndex = 4;
            this.labelTotalPercent.Text = "0%";
            // 
            // lableCurPercent
            // 
            this.lableCurPercent.AutoSize = true;
            this.lableCurPercent.Location = new System.Drawing.Point(87, 32);
            this.lableCurPercent.Name = "lableCurPercent";
            this.lableCurPercent.Size = new System.Drawing.Size(21, 12);
            this.lableCurPercent.TabIndex = 5;
            this.lableCurPercent.Text = "0%";
            // 
            // label_filename
            // 
            this.label_filename.AutoSize = true;
            this.label_filename.Location = new System.Drawing.Point(13, 9);
            this.label_filename.Name = "label_filename";
            this.label_filename.Size = new System.Drawing.Size(75, 12);
            this.label_filename.TabIndex = 7;
            this.label_filename.Text = "(현재파일명)";
            // 
            // FileProgressForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(391, 151);
            this.Controls.Add(this.label_filename);
            this.Controls.Add(this.lableCurPercent);
            this.Controls.Add(this.labelTotalPercent);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.progressTotal);
            this.Controls.Add(this.progressCur);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FileProgressForm";
            this.Text = "파일전송";
            this.Load += new System.EventHandler(this.FileProgressForm_Load);
            this.Shown += new System.EventHandler(this.FileProgressForm_Shown);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FileProgressForm_FormClosing);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ProgressBar progressCur;
        private System.Windows.Forms.ProgressBar progressTotal;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label labelTotalPercent;
        private System.Windows.Forms.Label lableCurPercent;
        private System.Windows.Forms.Label label_filename;
    }
}

 
posted by 뚱2
간단한 파일 탐색기를 구현했다.
Drag And Drop도 구현
Ctrl+마우스 DnD : 복사, 마우스 DnD : 이동


탐색기 갱신의 약간의 버그와 소스코드가 드러운데
나중을 위해서 그냥 저장... 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;


namespace TestExplorer

{

    public partial class MainForm : Form

    {

        private TreeNode sourceNode = null;


        public MainForm()

        {

            InitializeComponent();

        }


        private void LoadDrive()

        {

            DriveInfo[] drivers = DriveInfo.GetDrives();

            foreach (DriveInfo i in drivers)

            {

                if ( (i.DriveType & DriveType.Fixed) == DriveType.Fixed )

                {

                    TreeNode newNode1 = this.treeView1.Nodes.Add(i.Name);

                    TreeNode newNode2 = this.treeView2.Nodes.Add(i.Name);

                    DirectoryInfo di = new DirectoryInfo(i.Name);

                    try

                    {

                        if (di.GetFileSystemInfos().Count() > 0)

                        {

                            newNode1.Nodes.Add("temp");

                            newNode2.Nodes.Add("temp");

                        }

                    }

                    catch (Exception e)

                    {

                    }

                }

            }

        }


        private void RefreshNode(TreeNode sourceNode, TreeNode targetNode)

        {

        }


        private void Form1_Load(object sender, EventArgs e)

        {

            LoadDrive();

        }


        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)

        {

            // root는 제외

            //MessageBox.Show(e.Node.Text);

            e.Node.Nodes.Clear();

            string fullPath = e.Node.FullPath;

            DirectoryInfo di = new DirectoryInfo(fullPath);

            FileSystemInfo[] arrFsi = di.GetFileSystemInfos();

            e.Node.TreeView.BeginUpdate();

            foreach (FileSystemInfo i in arrFsi)

            {

                if ( (i.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden )

                {

                    TreeNode newNode = e.Node.Nodes.Add(i.Name);

                    DirectoryInfo newDI = new DirectoryInfo(i.FullName);

                    try

                    {

                        if (newDI.GetFileSystemInfos().Count() > 0)

                        {

                            newNode.Nodes.Add("temp");

                        }

                    }

                    catch (Exception ex)

                    {

                    }

                }

            }

            e.Node.TreeView.EndUpdate();

        }


        private void treeView1_MouseDown(object sender, MouseEventArgs e)

        {

            System.Console.WriteLine("treeView1_MouseDown");

            TreeViewHitTestInfo hitInfo = this.treeView1.HitTest(e.Location);

            if (hitInfo != null && hitInfo.Node != null)

            {

                TreeNode node = hitInfo.Node;

                System.Console.WriteLine(node.FullPath);


                // 현재 노드를 선택해준다.

                node.TreeView.SelectedNode = node;

            }

        }


        private void treeView1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)

        {

            System.Console.WriteLine("treeView1_QueryContinueDrag");

            if (e.EscapePressed)

            {

                e.Action = DragAction.Cancel;

            }

        }


        private void treeView2_DragEnter(object sender, DragEventArgs e)

        {

            System.Console.WriteLine("treeView2_DragEnter");

        }


        private void treeView2_DragOver(object sender, DragEventArgs e)

        {

            System.Console.WriteLine("treeView2_DragOver");

            if (e.Data.GetDataPresent(DataFormats.StringFormat))

            {

                if ((e.KeyState & 8) == 8)

                {

                    e.Effect = DragDropEffects.Copy;

                }

                else

                {

                    e.Effect = DragDropEffects.Move;

                }

            }

        }


        private void treeView2_DragDrop(object sender, DragEventArgs e)

        {

            System.Console.WriteLine("treeView2_DragDrop");

            if (e.Data.GetDataPresent(DataFormats.StringFormat))

            {

                string sourcePath = (string)e.Data.GetData(DataFormats.StringFormat);

                Point pt = new Point(MousePosition.X, MousePosition.Y);

                pt = this.treeView2.PointToClient(pt);

                TreeViewHitTestInfo hitInfo = this.treeView2.HitTest(pt);

                if (hitInfo != null && hitInfo.Node != null)

                {

                    string targetPath = hitInfo.Node.FullPath;


                    // 폴더 복사

                    if (Directory.Exists(sourcePath) == true

                         && Directory.Exists(targetPath) == true)

                    {

                        FileProgressForm form = new FileProgressForm();

                        form.SourcePath = sourcePath;

                        form.TargetPath = targetPath;


                        if (e.Effect == DragDropEffects.Move)

                        {

                            form.Action = FileProgressForm.ACTION_TYPE.MOVE;

                        }

                        else if (e.Effect == DragDropEffects.Copy)

                        {

                            form.Action = FileProgressForm.ACTION_TYPE.COPY;

                        }

                        DialogResult result = form.ShowDialog();

                        if (result == DialogResult.OK)

                        {

                            TreeView tree = hitInfo.Node.TreeView;

                            hitInfo.Node.TreeView.TopNode.Collapse();

                            hitInfo.Node.TreeView.TopNode.Expand();

                            hitInfo.Node.Collapse();

                            hitInfo.Node.Expand();

                            sourceNode.TreeView.TopNode.Collapse();

                            sourceNode.TreeView.TopNode.Expand();

                            sourceNode.Collapse();

                            sourceNode.Expand();

                        }

                        else if (result == DialogResult.Cancel)

                        {

                        }

                    }

                    // 파일 복사

                    else if (File.Exists(sourcePath) == true

                        && Directory.Exists(targetPath) == true)

                    {

                        FileProgressForm form = new FileProgressForm();

                        form.SourcePath = sourcePath;

                        form.TargetPath = targetPath;


                        if (e.Effect == DragDropEffects.Move)

                        {

                            form.Action = FileProgressForm.ACTION_TYPE.MOVE;

                        }

                        else if (e.Effect == DragDropEffects.Copy)

                        {

                            form.Action = FileProgressForm.ACTION_TYPE.COPY;

                        }

                        DialogResult result = form.ShowDialog();

                        if (result == DialogResult.OK)

                        {

                            TreeView tree = hitInfo.Node.TreeView;

                            hitInfo.Node.TreeView.TopNode.Collapse();

                            hitInfo.Node.TreeView.TopNode.Expand();

                            hitInfo.Node.Collapse();

                            hitInfo.Node.Expand();

                            sourceNode.TreeView.TopNode.Collapse();

                            sourceNode.TreeView.TopNode.Expand();

                            sourceNode.Collapse();

                            sourceNode.Expand();

                        }

                        else if (result == DialogResult.Cancel)

                        {

                        }

                    }

                    else

                    {

                        MessageBox.Show("파일이 존재하지 않거나, 복사하려는 곳이 폴더가 아닙니다.");

                    }

                }

            }

        }


        private void Main_Shown(object sender, EventArgs e)

        {

            //DialogResult result = MessageBox.Show("정식 버전을 구입하세요", "확인", MessageBoxButtons.YesNo);


            //if (result == DialogResult.No)

            //{

            //    this.Close();

            //}

            //else

            //{

            //    MessageBox.Show("정식 버전을 구입해 주셔서 감사합니다.");

            //}

        }


        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)

        {

            TreeNode node = e.Item as TreeNode;

            if (node != null )

            {

                System.Console.WriteLine(node.FullPath);


                string fullPath = node.FullPath;

                sourceNode = node;

                Console.WriteLine("treeView1_ItemDrag=" + fullPath);

                // DoDragDrop 시작

                DragDropEffects effects = DoDragDrop(fullPath, DragDropEffects.Copy | DragDropEffects.Move);


                // 트리 부모 노드를 갱신해 준다.

                if (effects == DragDropEffects.Move)

                {

                }

            }

        }


        private void treeView2_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)

        {

        }

    }

}


designer code 

namespace TestExplorer

{

    partial class MainForm

    {

        /// 


        /// 필수 디자이너 변수입니다.

        /// 


        private System.ComponentModel.IContainer components = null;


        /// 


        /// 사용 중인 모든 리소스를 정리합니다.

        /// 


        /// 관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }


        #region Windows Form 디자이너에서 생성한 코드


        /// 


        /// 디자이너 지원에 필요한 메서드입니다.

        /// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.

        /// 


        private void InitializeComponent()

        {

            this.splitContainer1 = new System.Windows.Forms.SplitContainer();

            this.treeView1 = new System.Windows.Forms.TreeView();

            this.treeView2 = new System.Windows.Forms.TreeView();

            this.splitContainer1.Panel1.SuspendLayout();

            this.splitContainer1.Panel2.SuspendLayout();

            this.splitContainer1.SuspendLayout();

            this.SuspendLayout();

            // 

            // splitContainer1

            // 

            this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

                        | System.Windows.Forms.AnchorStyles.Left)

                        | System.Windows.Forms.AnchorStyles.Right)));

            this.splitContainer1.Location = new System.Drawing.Point(13, 13);

            this.splitContainer1.Name = "splitContainer1";

            // 

            // splitContainer1.Panel1

            // 

            this.splitContainer1.Panel1.Controls.Add(this.treeView1);

            // 

            // splitContainer1.Panel2

            // 

            this.splitContainer1.Panel2.Controls.Add(this.treeView2);

            this.splitContainer1.Size = new System.Drawing.Size(659, 387);

            this.splitContainer1.SplitterDistance = 327;

            this.splitContainer1.TabIndex = 2;

            // 

            // treeView1

            // 

            this.treeView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

                        | System.Windows.Forms.AnchorStyles.Left)

                        | System.Windows.Forms.AnchorStyles.Right)));

            this.treeView1.HotTracking = true;

            this.treeView1.Location = new System.Drawing.Point(3, 3);

            this.treeView1.Name = "treeView1";

            this.treeView1.Size = new System.Drawing.Size(321, 381);

            this.treeView1.TabIndex = 4;

            this.treeView1.QueryContinueDrag += new System.Windows.Forms.QueryContinueDragEventHandler(this.treeView1_QueryContinueDrag);

            this.treeView1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);

            this.treeView1.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView1_BeforeExpand);

            this.treeView1.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeView1_ItemDrag);

            // 

            // treeView2

            // 

            this.treeView2.AllowDrop = true;

            this.treeView2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

                        | System.Windows.Forms.AnchorStyles.Left)

                        | System.Windows.Forms.AnchorStyles.Right)));

            this.treeView2.HotTracking = true;

            this.treeView2.Location = new System.Drawing.Point(3, 3);

            this.treeView2.Name = "treeView2";

            this.treeView2.Size = new System.Drawing.Size(322, 381);

            this.treeView2.TabIndex = 3;

            this.treeView2.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeView1_BeforeExpand);

            this.treeView2.NodeMouseHover += new System.Windows.Forms.TreeNodeMouseHoverEventHandler(this.treeView2_NodeMouseHover);

            this.treeView2.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeView2_DragDrop);

            this.treeView2.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeView2_DragEnter);

            this.treeView2.DragOver += new System.Windows.Forms.DragEventHandler(this.treeView2_DragOver);

            // 

            // MainForm

            // 

            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(684, 412);

            this.Controls.Add(this.splitContainer1);

            this.Name = "MainForm";

            this.Text = "TestExplorer";

            this.Load += new System.EventHandler(this.Form1_Load);

            this.Shown += new System.EventHandler(this.Main_Shown);

            this.splitContainer1.Panel1.ResumeLayout(false);

            this.splitContainer1.Panel2.ResumeLayout(false);

            this.splitContainer1.ResumeLayout(false);

            this.ResumeLayout(false);


        }


        #endregion


        private System.Windows.Forms.SplitContainer splitContainer1;

        private System.Windows.Forms.TreeView treeView2;

        private System.Windows.Forms.TreeView treeView1;


    }

}


posted by 뚱2

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

[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
[C#] internal 지정자  (0) 2012.03.12
[즐겨찾기] 무료서적 Inside C# 2nd  (0) 2012.03.10
posted by 뚱2

[SourceGrid] 즐겨찾기

.Net/SourceGrid 2012. 3. 14. 14:35
링크 : http://sourcegrid.codeplex.com/ 
문서 : http://sourcegrid.codeplex.com/documentation 

이번에 프로젝트를 위해서 무료 그리드를 찾던중 발견한 그리드 몰랐는데 역사가 오래되었다.
개발툴을 만드는 용도기 때문에 기본 기능으로 충분할 것 같다.

 
posted by 뚱2

[C#] internal 지정자

.Net/C# 2012. 3. 12. 14:26

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

[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
[즐겨찾기] 무료서적 Inside C# 2nd  (0) 2012.03.10
posted by 뚱2

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

[C#] log4net  (0) 2012.04.03
[C#] vshosting.exe 가 뭘까요?  (0) 2012.03.26
[C#] Dynamic Method Call With Out Parameter  (0) 2012.03.22
[즐겨찾기] C# TreeView MultiSelect  (0) 2012.03.15
[C#] internal 지정자  (0) 2012.03.12
posted by 뚱2
32bit :C:\Program Files \Microsoft Visual Studio 8\SDK\v2.0\Bin
64bit : C:\Program Files (x86)\Microsoft Visual Studio 8\SDK\v2.0\Bin 
posted by 뚱2