GSI

C# USB 인식 심플한 코드

C# 2009. 12. 15. 18:25 |


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

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool bFind = false;

            // USB 상태 체크
            DriveInfo [] diArray = DriveInfo.GetDrives();
            foreach (DriveInfo di in diArray)
            {
                if (di.IsReady == true && di.DriveType == DriveType.Removable)
                {
                    bFind = true;
                    break;
                }
            }

            label1.Text = (bFind == true) ? "존재합니다." : "없습니다.";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }
    }

Posted by gsi
:


    public partial class ucPanel : UserControl
    {
        public ucPanel()
        {
            InitializeComponent();

            //
            backgroundWorker1.RunWorkerAsync();
        }

        static public Font ChangeFontSize2(Font font, float fontSize, GraphicsUnit unit)
        {
            if (font != null)
            {
                float currentSize = font.Size;
                if (currentSize != fontSize)
                {
                    font = new Font(font.Name, fontSize,
                        font.Style, unit,
                        font.GdiCharSet, font.GdiVerticalFont);
                }
            }
            return font;
        }

        public delegate void OnAddNode(string title, int x, int y);
        public void AddNode(string title, int x, int y)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new OnAddNode(this.AddNode), new object[] { title, x, y });
                return;
            }

            // 객체 추가
            Label lbl2 = new Label();
            lbl2.AutoSize = true;
            lbl2.Text = title;
            lbl2.Font = ChangeFontSize2(lbl2.Font, lbl2.Font.Size * 2, GraphicsUnit.Pixel);
            lbl2.Left = x;
            lbl2.Top = y;
            this.Controls.Add(lbl2);

            ucNode ucn = new ucNode();
            ucn.Left = x;
            ucn.Top = y;
            this.Controls.Add(ucn);
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int breakCount = 0;
            Random rand = new Random();

            while (true)
            {
                //
                this.Invoke(new OnAddNode(this.AddNode), new object[] { "test", rand.Next(10, 738), rand.Next(10, 460) });

                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));

                //
                breakCount++;
                if (breakCount > 100)
                {
                    break;
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }
    }

Posted by gsi
:

WebBrowser 처리방식.. 참..

WPF 2009. 12. 7. 06:09 |


2일 정도 자료를 찾아 보고 했지만.
WebBrowser 는 왜 WPF의 렌더링 방식과 차이가 있는지 모르겠다.
왜냐하면 WebBrowser 위에 다른걸 그리고 싶었지만.
되지 않더라..

그래서 자료를 보다 보니. BitmapSource 라는걸 사용해서 WPF의 렌더링 방식에
맞출수 있다는걸 알았다.
뭐 용어는 잘 모르겠고 암튼 이런 방식인게다. 쩝..
산넘어 산인거지..

우선 이걸 해결 하고 나니 몇가지 더 테스트 할게 남아 있다.
실제 WebBrowser는 숨겨 놓고 Image 같은데 실시간으로 뿌리면서 드로잉 해야 한다는 것과
숨겨 놓은 웹의 Mouse, Keyboard 등의 접근을 또 어떻게 처리 해야 하느냔데..

암튼 더 고민해봐야 할듯 하다.
아래 자료는 최종 코드...

-- Source --
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="600" Width="1000" xmlns:my="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration">

    <Grid>
        <WebBrowser x:Name="webbrowser" Source="http://www.naver.com" Margin="0,0,437,199" />
       
        <Button Height="23" HorizontalAlignment="Right" Margin="0,104,307,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">Button</Button>
        <Image HorizontalAlignment="Right" Margin="0,178,18,21" Name="image1" Stretch="Fill" Width="399" />
    </Grid>

</Window>

..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;


namespace WpfApplication1
{
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : Window
    {
        BitmapSource bitmapsource = null;

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
       
        public Window1()
        {
            InitializeComponent();
        }

        BitmapSource GetScreenInt()
        {
            Bitmap bm = new Bitmap((int)300, (int)300);
            IntPtr hBitmap = bm.GetHbitmap();
            Graphics g = Graphics.FromImage(bm);
            PrintWindow(this.webbrowser.Handle, g.GetHdc(), 0);

            g.ReleaseHdc();

            g.Flush();

            BitmapSource src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bm.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
            src.Freeze();

            bm.Dispose();
            bm = null;
            DeleteObject(hBitmap);

            return src;

        }
       
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.image1.Source = null;
            this.image1.Source = GetScreenInt();
        }
    } 
}

Posted by gsi
:

SELECT REPLACE(CONVERT(varchar(max),textvalue), Substring(textvalue,Len(textvalue)-1,2),'**')
from TBL_TEST_DB

textvalue의 값이 12345 라고 하면 123** 로 치환한다.
Posted by gsi
:


구글이라던지 이곳저곳 찾아 보면 상당히 많은 예제가 나오는거 같다.
GsiClip을 제작중에 DB에 이미지를 데이터로 추가 해야 하는 부분에
단위 테스트에 사용한 소스 코드임. (테스트 수행)

        private void button1_Click(object sender, EventArgs e)
        {
            // 이미지를 DB로 저장한다.
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ImageSave(openFileDialog1.FileName);

                MessageBox.Show("저장완료");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 이미지를 DB에서 로드한다.
            dsImageTableAdapters.Test1TableAdapter adapter =
                new ImageSaveDB.dsImageTableAdapters.Test1TableAdapter();
            dsImage.Test1DataTable table =
                new dsImage.Test1DataTable();

            adapter.Fill(table);

            if (table.Count > 0)
            {
                pictureBox1.Image = byteArrayToImage(table[0].Content2);
            }
        }

        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        byte[] ReadFile(string sPath)
        {
            byte[] data = null;

            //
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;
            //
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
            //
            BinaryReader br = new BinaryReader(fStream);
            //
            data = br.ReadBytes((int)numBytes);

            return data;
        }

        private void ImageSave(string filename)
        {
            byte[] imageData = ReadFile(filename);

            //
            dsImageTableAdapters.Test1TableAdapter adapter =
                new ImageSaveDB.dsImageTableAdapters.Test1TableAdapter();

            adapter.Insert(imageData);
        }

Posted by gsi
: