BindingList<ComboData> _comboItems = new BindingList<ComboData>(); // ComboBox의 DataSource 적용된것


private void Combo_DrawItem(object sender, DrawItemEventArgs e)

        {

            Brush brush = null;

            ComboBox combo = (ComboBox)sender;


            if (combo == null || _comboItems == null)

            {

                return;

            }


            if (대상인 색깔..)

            {

                //백그라운드 색

                e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);

                //글자 색

                brush = ((e.State & DrawItemState.Selected) > 0) ? SystemBrushes.HotTrack : SystemBrushes.ControlText;

                e.Graphics.DrawString(_comboItems[e.Index].Text, combo.Font, brush, e.Bounds);

            }

            else

            {

                e.DrawBackground();

                //백그라운드 색

                e.Graphics.FillRectangle(Brushes.DarkGray, e.Bounds);

                //글자 색

                brush = ((e.State & DrawItemState.Selected) > 0) ? SystemBrushes.HighlightText : SystemBrushes.ControlText;

                e.Graphics.DrawString(_comboItems[e.Index].Text, combo.Font, brush, e.Bounds);

                e.DrawFocusRectangle();

            }

        }

Posted by Lich King
,

    public interface IFormDataInterface

    {

        void SetData(String Data);

    }

    

    public partial class Form1 : Form, IFormDataInterface

    {

        public Form1()

        {

            InitializeComponent();

        }


        private void button1_Click(object sender, EventArgs e)

        {

            Form2 frm = new Form2(this as IFormDataInterface);

            frm.Show();

        }

        public void SetData(String Data)

        {

            textBox1.Text = Data;

        }

    }


    public partial class Form2 : Form

    {

        private IFormDataInterface frm = null;

        public Form2(IFormDataInterface frm)

        {

            InitializeComponent();

            this.frm = frm;

        }


        private void button1_Click(object sender, EventArgs e)

        {

            frm.SetData(textBox1.Text);

        }

    }

Posted by Lich King
,

            AutoScroll = false;

            HorizontalScroll.Enabled = false;

            AutoScroll = true;


하면된다.

이렇게 안하면 수평 스크롤이 안없어진다.

버그가 있다.

Posted by Lich King
,

생성자

            TableLayoutPanel1.MouseWheel += new MouseEventHandler(DoNothing_MouseWheel);



함수

        private void DoNothing_MouseWheel(object sender, EventArgs e)
        {
            HandledMouseEventArgs handledMouseEventArgs = (HandledMouseEventArgs)e;
            handledMouseEventArgs.Handled = true;
        }

TableLayoutPanel  이벤트

        private void coTableLayoutPanel1_MouseHover(object sender, EventArgs e)
        {
            TableLayoutPanel1.Focus();
        }


Posted by Lich King
,

    public static class NativeMethods

    {

        public static int WM_SETREDRAW = 0x000B; //uint WM_SETREDRAW

        public static int WS_EX_COMPOSITED = 0x02000000;

        

        [DllImport("user32.dll", CharSet = CharSet.Auto)]

        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); //UInt32 Msg

    }




class DoubleBufferTableLayoutPanel : TableLayoutPanel

    {



        public DoubleBufferTableLayoutPanel()

        {

            SetStyle(ControlStyles.DoubleBuffer, true);

        }


        protected override void OnCreateControl()

        {

            base.OnCreateControl();

            this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.CacheText, true);

        }


        protected override CreateParams CreateParams

        {

            get

            {

                CreateParams cp = base.CreateParams;

                cp.ExStyle |= NativeMethods.WS_EX_COMPOSITED;

                return cp;

            }

        }


        public void BeginUpdate()

        {

            NativeMethods.SendMessage(this.Handle, NativeMethods.WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);

        }


        public void EndUpdate()

        {

            NativeMethods.SendMessage(this.Handle, NativeMethods.WM_SETREDRAW, new IntPtr(1), IntPtr.Zero);

            Parent.Invalidate(true);

        }

    }



DoubleBufferTableLayoutPanel  이것을 쓴다.

Posted by Lich King
,

        private void AddNewTab(Form frm)

        {

            TabPage tab = new TabPage(frm.Text);

            frm.TopLevel = false;

            frm.Parent = tab;

            frm.Visible = true;

            dataMakerTabControl.TabPages.Add(tab);

            frm.Location = new Point((tab.Width - frm.Width) / 2, (tab.Height - frm.Height) / 2);

            frm.Height = frm.Height;

        }

선언하고

다음과같이 호출한다.


AddNewTab(new Form2());



Posted by Lich King
,

참조추가 한 이후


C:\Program Files\Microsoft Office\Office12 (아니면 오피스 깔려있는 곳)


에 가서 Excel.exe 를 추가하면


interop dll. 참조가 완료된다.


해당 에러의 원인은 경로가 다르기 때문이다.

Posted by Lich King
,

dll 파일을 잘못 만들어서 그런다.


클래스 라이브러리파일에 있는 AssemblyInfo.cs 에서

[assembly: InternalsVisibleTo("참조할 어셈블리 이름")] 을 추가한다.


참조하기 위한 프로젝트의 어셈블리 이름은 

Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);


과 같이 확인할 수 있다. 일반적으로 프로젝트의 이름이다.

Posted by Lich King
,



        private void FileEncrypt(string inputFile, string outputFile, string password)

        {

            //http://stackoverflow.com/questions/27645527/aes-encryption-on-large-files


            //generate random salt

            byte[] salt = GenerateRandomSalt();


            FileStream fsCrypt = new FileStream(outputFile, FileMode.Create);


            //convert password string to byte arrray

            byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);


            //Set Rijndael symmetric encryption algorithm

            RijndaelManaged AES = new RijndaelManaged();

            AES.KeySize = 256;

            AES.BlockSize = 128;

            AES.Padding = PaddingMode.PKCS7;


            //http://stackoverflow.com/questions/2659214/why-do-i-need-to-use-the-rfc2898derivebytes-class-in-net-instead-of-directly

            //"What it does is repeatedly hash the user password along with the salt." High iteration counts.


    // 보안성을 중시하면 다음 줄을 쓴다. 속도는 많이 느리다.

            //var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);

            //AES.Key = key.GetBytes(AES.KeySize / 8);

            //AES.IV = key.GetBytes(AES.BlockSize / 8);


            // 속도를 중시하면 다음 줄을 쓴다. 속도는 빠르다.

            AES.Key = Encoding.UTF8.GetBytes(password);

            AES.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };



            //Cipher modes: http://security.stackexchange.com/questions/52665/which-is-the-best-cipher-mode-and-padding-mode-for-aes-encryption

            AES.Mode = CipherMode.CFB;


            // write salt to the begining of the output file, so in this case can be random every time

            fsCrypt.Write(salt, 0, salt.Length);


            CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write);


            FileStream fsIn = new FileStream(inputFile, FileMode.Open);


            //create a buffer (1mb) so only this amount will allocate in the memory and not the whole file

            byte[] buffer = new byte[1048576];

            int read;


            try

            {

                while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)

                {

                    Application.DoEvents(); // -> for responsive GUI, using Task will be better!

                    cs.Write(buffer, 0, read);

                }


                // Close up

                fsIn.Close();

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

            }

            finally

            {

                cs.Close();

                fsCrypt.Close();

            }

        }



        private void FileDecrypt(string inputFile, string outputFile, string password)

        {

            byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            byte[] salt = new byte[32];


            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

            fsCrypt.Read(salt, 0, salt.Length);


            RijndaelManaged AES = new RijndaelManaged();

            AES.KeySize = 256;

            AES.BlockSize = 128;


    // 보안성을 중시하면 다음 줄을 쓴다. 속도는 많이 느리다.

            //var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);

            //AES.Key = key.GetBytes(AES.KeySize / 8);

            //AES.IV = key.GetBytes(AES.BlockSize / 8);


    // 속도를 중시하면 다음 줄을 쓴다. 속도는 빠르다.

            AES.Key = Encoding.UTF8.GetBytes(password);

            AES.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };



            AES.Padding = PaddingMode.PKCS7;

            AES.Mode = CipherMode.CFB;


            CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);


            FileStream fsOut = new FileStream(outputFile, FileMode.Create);


            int read;

            byte[] buffer = new byte[1048576];


            try

            {

                while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)

                {

                    Application.DoEvents();

                    fsOut.Write(buffer, 0, read);

                }

            }

            catch (CryptographicException ex_CryptographicException)

            {

                Console.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error: " + ex.Message);

            }


            try

            {

                cs.Close();

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error by closing CryptoStream: " + ex.Message);

            }

            finally

            {

                fsOut.Close();

                fsCrypt.Close();

            }

        }



inputFile : 암호화할 파일 디렉토리

outputFile : 암호화되어 저장하기 위한 파일 디렉토리 

password : 암호화 키


Rfc2898DeriveBytes의 GetBytes는 Key를 해쉬화하여 각 파일에 여러개의 Key를 주입한 효과를 준다. 그러나 보안성이 강화되는 만큼 너무 느리다..

var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000); 에서 50000을 100000을 넣으면 보안성이 더강화된다.




이 알고리즘을 사용하기 위해서는 사용클래스에



        [DllImport("KERNEL32.DLL", EntryPoint = "RtlZeroMemory")]

        public static extern bool ZeroMemory(IntPtr Destination, int Length);


        /// <summary>

        /// Creates a random salt that will be used to encrypt your file. This method is required on FileEncrypt.

        /// salt : randomly string of byte unit

        /// </summary>

        /// <returns></returns>

        private static byte[] GenerateRandomSalt()

        {

            byte[] data = new byte[32];


            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())

            {

                for (int i = 0; i < 10; i++)

                {

                    // Fille the buffer with the generated data

                    rng.GetBytes(data);

                }

            }


            return data;

        }


를 선언하고


public void EncryptFile(){

    //AES256의 key는 32bit

            string password = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";


            // For additional security Pin the password of your files

            GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);


            FileEncrypt(dirFilePath, encryptFilePath, password);


            // To increase the security of the encryption, delete the given password from the memory !

            ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);

            gch.Free();


}


public void DecryptFile(){


    //AES256의 key는 32bit

            string password = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";


            // For additional security Pin the password of your files

            GCHandle gch = GCHandle.Alloc(password, GCHandleType.Pinned);


            FileDecrypt(dirFilePath, decryptFilePath, password);

            // To increase the security of the decryption, delete the used password from the memory !

            ZeroMemory(gch.AddrOfPinnedObject(), password.Length * 2);

            gch.Free();

}


다음과 같은 방식으로 쓰면 된다.


Posted by Lich King
,

Form에 다음을 선언한다.




   protected virtual bool DoubleBuffered { get; set; }



   public static class Extensions

    {

        public static void DoubleBuffered(this Control control, bool enabled)

        {

            var prop = control.GetType().GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);

            prop.SetValue(control, enabled, null);

        }

    }


2개를 선언하고 리스트뷰에 


            statusListview.DoubleBuffered(true);


를 쓴다.

Form1_Load에 쓰면 됨. 일반적으로


Posted by Lich King
,