ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • WPF Splash
    C# 2022. 6. 1. 18:31

    메인윈도우

    랜덤으로 색을 20칸의 색을 칠한 후 DB에 저장하는 방법을 알아보자

      <Grid>
            <Button Content="Random 색깔표시" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20,20,0,0" Width="150" x:Name="btnRandom" Click="btnRandom_Click"/>
            <Button Content="DB에 저장된 색깔표시" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20,50,0,0" Width="150" x:Name="btnDB" Click="btnDB_Click"/>
            <Button Content="DB Reset" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,20,20,0" Width="150" x:Name="btnReset" Click="btnReset_Click" />
            <Button Content="종료" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,50,20,0" Width="150" x:Name="btnExit" Click="btnExit_Click" />
            <TextBlock x:Name="lblDate" HorizontalAlignment="Left" TextAlignment="Center" Margin="275,20,0,0" Width="150" VerticalAlignment="Top"/>
            <TextBlock x:Name="lblTime" HorizontalAlignment="Left" TextAlignment="Center" Margin="275,50,0,0" Width="150" VerticalAlignment="Top"/>
            <Grid Margin="20,90,20,20" Background="AntiqueWhite" Height="200" VerticalAlignment="Top">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <!--첫번째 줄-->
                <Border Margin="1" x:Name="bd1" Grid.Row="0" Grid.Column="0"/>
                <Border Margin="1" x:Name="bd2" Grid.Row="0" Grid.Column="1"/>
                <Border Margin="1" x:Name="bd3" Grid.Row="0" Grid.Column="2"/>
                <Border Margin="1" x:Name="bd4" Grid.Row="0" Grid.Column="3"/>
                <Border Margin="1" x:Name="bd5" Grid.Row="0" Grid.Column="4"/>
                <!--두번째 줄-->
                <Border Margin="1" x:Name="bd6" Grid.Row="1" Grid.Column="0"/>
                <Border Margin="1" x:Name="bd7" Grid.Row="1" Grid.Column="1"/>
                <Border Margin="1" x:Name="bd8" Grid.Row="1" Grid.Column="2"/>
                <Border Margin="1" x:Name="bd9" Grid.Row="1" Grid.Column="3"/>
                <Border Margin="1" x:Name="bd10" Grid.Row="1" Grid.Column="4"/>
                <!--세번째 줄-->
                <Border Margin="1" x:Name="bd11" Grid.Row="2" Grid.Column="0"/>
                <Border Margin="1" x:Name="bd12" Grid.Row="2" Grid.Column="1"/>
                <Border Margin="1" x:Name="bd13" Grid.Row="2" Grid.Column="2"/>
                <Border Margin="1" x:Name="bd14" Grid.Row="2" Grid.Column="3"/>
                <Border Margin="1" x:Name="bd15" Grid.Row="2" Grid.Column="4"/>
                <!--네번째 줄-->
                <Border Margin="1" x:Name="bd16" Grid.Row="3" Grid.Column="0"/>
                <Border Margin="1" x:Name="bd17" Grid.Row="3" Grid.Column="1"/>
                <Border Margin="1" x:Name="bd18" Grid.Row="3" Grid.Column="2"/>
                <Border Margin="1" x:Name="bd19" Grid.Row="3" Grid.Column="3"/>
                <Border Margin="1" x:Name="bd20" Grid.Row="3" Grid.Column="4"/>
    
            </Grid>
            <ListBox Background="AliceBlue" x:Name="lstDB" Margin="20,310,20,20"/>
        </Grid>
    </Window>

    세로 4 가로 5로 20칸을 만들어 각각에 이름을 추가시키고 위치를 지정하였다.

     public MainWindow()
            {
                InitializeComponent();
                borderList = new List<Border> { bd1, bd2,bd3,bd4,bd5,bd6,bd7,bd8,bd9,bd10,bd11,bd12,bd13,bd14,bd15,bd16,bd17,bd18,bd19,bd20 };
                t.Interval = new TimeSpan(0, 0, 1);
                t.Tick += T_Tick;
            }

    borederList에 xml에 만들어던 20칸들을 넣어주고 타임인터벌을 1초로 설정한다.

    private void T_Tick(object sender, EventArgs e)
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string time = DateTime.Now.ToString("HH:mm:ss");
                lblDate.Text = date;
                lblTime.Text = time;
    
                
                byte[] colors = new byte[20];
                for (int i = 0; i < 20; i++)
                {
                    colors[i] = (byte)(r.Next(256));
                    borderList[i].Background
                      = new SolidColorBrush(
                        Color.FromRgb((byte)0, (byte)0, colors[i]));
                }
                string s = "";
                s += date + " " + time + " ";
                for (int i = 0; i < borderList.Count; i++)
                {
                    s += colors[i] + " ";
                }
                lstDB.Items.Add(s);
    
                //리스트박스의 스크롤
                lstDB.SelectedIndex = index++;
                lstDB.ScrollIntoView(lstDB.SelectedItem);
    
                //DB에 저장
                string sql = string.Format("INSERT INTO Table VALUES ('{0}', '{1}'", date,time);
                for (int i = 0; i < 20; i++)
                {
                    sql += ", " + colors[i];
                }
                sql += ")";
                MessageBox.Show(sql);
                using (SqlConnection conn = new SqlConnection(connStr))
                using (SqlCommand comm = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    comm.ExecuteNonQuery();
                }
            }

    위의 코드는 초단위로 렌덤색을 설정하며 DB에 저장하게 된다 

    이때 저장되는 형식은 이러하다. 랜덤의로 컬러를 지정하지만 RGB중 B의 값만 조정하여 색을 표시하기때문에 R,G는 0으로 고정되어있다.

      private void btnRandom_Click(object sender, RoutedEventArgs e)
            {
                if (flag == false)
                {
                    t.Start();
                    btnRandom.Content = "중지";
                    flag = true;
                }
                else
                {
                    t.Stop();
                    btnRandom.Content = "Random색깔표시";
                    flag = false;
                }
              
            }

    렌덤 저장 버튼으로 누르면 t.Start를 통해 위의 코드를 실행시켜 렌덤 색을 표시하게 하였다.

     private void btnDB_Click(object sender, RoutedEventArgs e)
            {
                lstDB.Items.Clear();
    
                string sql = "SELECT * FROM Talbe";
                int[] colors=new int[20];
                using(SqlConnection conn = new SqlConnection(connStr))
                using(SqlCommand comm = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    SqlDataReader reader=comm.ExecuteReader();
    
                    string s = "";
                    while (reader.Read())
                    {
                        s = "";
                        lblDate.Text = reader["Date"].ToString();
                        s+=lblDate.Text+" ";
                        lblTime.Text = reader["Time"].ToString();
                        s += lblTime.Text + " ";
                        for (int i = 0; i < 20; i++)
                        {
                            colors[i] = int.Parse(reader[i + 3].ToString());
                            s += colors[i] + " ";
                        }
                        lstDB.Items.Add(s);
                        lstDB.SelectedIndex = id++;
                        lstDB.ScrollIntoView(lstDB.SelectedItem);
    
                        for(int i = 0; i < colors.Length; i++)
                        {
                            borderList[i].Background=new SolidColorBrush(Color.FromRgb(0,0,(byte)colors[i]));
                        }
                        //WPF delay 주기
                        Dispatcher.Invoke((ThreadStart)(() => { }),DispatcherPriority.ApplicationIdle);
                        Thread.Sleep(20); //20ms
                    }
                }
            }

    위 코드는 DB에 저장되어 있는 코드를 읽는다.

       private void btnReset_Click(object sender, RoutedEventArgs e)
            {
                lstDB.Items.Clear();
                string sql = "DELETE FROM Talbe";
                using (SqlConnection conn = new SqlConnection(connStr))
                using (SqlCommand comm = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    comm.ExecuteNonQuery();
                }
            }

    위 코드는 리셋버튼으로 DB의 저장값을 리셋시킨다.

       private void btnExit_Click(object sender, RoutedEventArgs e)
            {
                this.Close();
            }

    Exit버튼으로 프로그램을 종료시킨다.

    DB에 저장하기위에 위와 같이 설정해준다. 칸의 수의 맞게 p1~p20까지 int로 설정

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Threading;
    using System.Data.SqlClient;
    using System.Threading;
    
    namespace _038_Splash
    {
        
        public partial class MainWindow : Window
        {
            string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\konyang\source\repos\VP01\038_Splash\Colors.mdf;Integrated Security=True";
            List<Border> borderList;
            DispatcherTimer t = new DispatcherTimer();
            Random r=new Random();
    
            
            public MainWindow()
            {
                InitializeComponent();
                borderList = new List<Border> { bd1, bd2,bd3,bd4,bd5,bd6,bd7,bd8,bd9,bd10,bd11,bd12,bd13,bd14,bd15,bd16,bd17,bd18,bd19,bd20 };
                t.Interval = new TimeSpan(0, 0, 1);
                t.Tick += T_Tick;
            }
            int index=0;
            private void T_Tick(object sender, EventArgs e)
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string time = DateTime.Now.ToString("HH:mm:ss");
                lblDate.Text = date;
                lblTime.Text = time;
    
                
                byte[] colors = new byte[20];
                for (int i = 0; i < 20; i++)
                {
                    colors[i] = (byte)(r.Next(256));
                    borderList[i].Background
                      = new SolidColorBrush(
                        Color.FromRgb((byte)0, (byte)0, colors[i]));
                }
                string s = "";
                s += date + " " + time + " ";
                for (int i = 0; i < borderList.Count; i++)
                {
                    s += colors[i] + " ";
                }
                lstDB.Items.Add(s);
    
                //리스트박스의 스크롤
                lstDB.SelectedIndex = index++;
                lstDB.ScrollIntoView(lstDB.SelectedItem);
    
                //DB에 저장
                string sql = string.Format("INSERT INTO Table VALUES ('{0}', '{1}'", date,time);
                for (int i = 0; i < 20; i++)
                {
                    sql += ", " + colors[i];
                }
                sql += ")";
                MessageBox.Show(sql);
                using (SqlConnection conn = new SqlConnection(connStr))
                using (SqlCommand comm = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    comm.ExecuteNonQuery();
                }
            }
            bool flag =false;
            private void btnRandom_Click(object sender, RoutedEventArgs e)
            {
                if (flag == false)
                {
                    t.Start();
                    btnRandom.Content = "중지";
                    flag = true;
                }
                else
                {
                    t.Stop();
                    btnRandom.Content = "Random색깔표시";
                    flag = false;
                }
              
            }
            int id=0;
            private void btnDB_Click(object sender, RoutedEventArgs e)
            {
                lstDB.Items.Clear();
    
                string sql = "SELECT * FROM Talbe";
                int[] colors=new int[20];
                using(SqlConnection conn = new SqlConnection(connStr))
                using(SqlCommand comm = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    SqlDataReader reader=comm.ExecuteReader();
    
                    string s = "";
                    while (reader.Read())
                    {
                        s = "";
                        lblDate.Text = reader["Date"].ToString();
                        s+=lblDate.Text+" ";
                        lblTime.Text = reader["Time"].ToString();
                        s += lblTime.Text + " ";
                        for (int i = 0; i < 20; i++)
                        {
                            colors[i] = int.Parse(reader[i + 3].ToString());
                            s += colors[i] + " ";
                        }
                        lstDB.Items.Add(s);
                        lstDB.SelectedIndex = id++;
                        lstDB.ScrollIntoView(lstDB.SelectedItem);
    
                        for(int i = 0; i < colors.Length; i++)
                        {
                            borderList[i].Background=new SolidColorBrush(Color.FromRgb(0,0,(byte)colors[i]));
                        }
                        //WPF delay 주기
                        Dispatcher.Invoke((ThreadStart)(() => { }),DispatcherPriority.ApplicationIdle);
                        Thread.Sleep(20); //20ms
                    }
                }
            }
    
            private void btnReset_Click(object sender, RoutedEventArgs e)
            {
                lstDB.Items.Clear();
                string sql = "DELETE FROM Talbe";
                using (SqlConnection conn = new SqlConnection(connStr))
                using (SqlCommand comm = new SqlCommand(sql, conn))
                {
                    conn.Open();
                    comm.ExecuteNonQuery();
                }
            }
    
            private void btnExit_Click(object sender, RoutedEventArgs e)
            {
                this.Close();
            }
        }
    }

    전체 코드이다.

    실행화면

    실행 화면이다.

    'C#' 카테고리의 다른 글

    WPF 시계만들기 (Rotation 사용)  (0) 2022.06.16
    WPF 시계만들기  (0) 2022.06.16
    WPF LOGIN  (0) 2022.05.25
    ACCESS를 사용한 DB연결 -2  (0) 2022.05.11
    ACCESS를 사용한 DB연결 -1  (0) 2022.05.04

    댓글

Designed by Tistory.