Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts
2013/05/07
[C#] WPF 윈도우를 마우스 드래그로 이동하기
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)<
{
base.OnMouseLeftButtonDown(e);
this.DragMove();
}
Original Post : http://neodreamer-dev.tistory.com/705
Labels:
c sharp
,
c#
,
Move Window
,
TistoryOldPost
,
WPF
[C#] 폼을 마우스 드래깅으로 이동하기
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_NCHITTEST:
{
base.WndProc(ref m);
if ((int)m.Result == HTCLIENT)
{
m.Result = (IntPtr)HTCAPTION;
}
return;
}
break;
}
base.WndProc(ref m);
}
출처: http://support.microsoft.com/kb/320687/en-u
Original Post : http://neodreamer-dev.tistory.com/704
Labels:
c sharp
,
c#
,
Form Dragging
,
Form Move
,
TistoryOldPost
,
폼 이동
2012/02/24
C#에서 OpenCV 사용하기 - OpenCVSharp
C#에서 OpenCV를 사용하기 위해 OpenCV wrapper for .Net Framework 가 필요하다.
OpenCvSharp-2.3.1-x86-20120218.zip
간단한 테스트에는 모든 파일이 필요 없고 OpenCvSharp.dll 만 이용해도 된다. 다른 여러 파일이 있지만 기본 기능은
OpenCvSharp.dll 만 있으면 되는 것으로 보인다.
Visual Studio 2010에서 Form Application을 만들고 Reference로 OpenCvSharp.dll 파일을 추가한다.
이제 Project에 간단한 OpenCV 코드를 작성한다.
아래 코드는 이미지를 불러들여 창으로 보여주는 아주 간단한 코드 이다.
그리고나서 컴파일을 하고 실행 파일이 있는 project/bin/Debug 경로에 Sample-2.3.1-20111229.zip 파일에 있는 dll 파일들을 복사해 두고 실행 테스트를 해 보았다.
하지만 실행시 OpenCV 관련 코드 실행시 에러가 발생하였다. 그래서 Visual C++ 2010 컴파일러로 직접 컴파일 한 dll 파일들 중 아래 세개 파일을 복사해 두었다.
opencv_core231.dll
opencv_highgui231.dll
opencv_imgproc231.dll
그 후로는 정상 동작을 하였다. 이제 C#으로 OpenCV를 활용한 프로그램을 만들어 봐야겠다.&
Original Post : http://neodreamer-dev.tistory.com/647
OpenCvSharp-2.3.1-x86-20120218.zip
간단한 테스트에는 모든 파일이 필요 없고 OpenCvSharp.dll 만 이용해도 된다. 다른 여러 파일이 있지만 기본 기능은
OpenCvSharp.dll 만 있으면 되는 것으로 보인다.
Visual Studio 2010에서 Form Application을 만들고 Reference로 OpenCvSharp.dll 파일을 추가한다.
이제 Project에 간단한 OpenCV 코드를 작성한다.
아래 코드는 이미지를 불러들여 창으로 보여주는 아주 간단한 코드 이다.
private void btnLoadImage_Click(object sender, EventArgs e)
{
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
IplImage iplImg = new IplImage(dlgOpen.FileName);
Cv.ShowImage("Image", iplImg);
}
}
그리고나서 컴파일을 하고 실행 파일이 있는 project/bin/Debug 경로에 Sample-2.3.1-20111229.zip 파일에 있는 dll 파일들을 복사해 두고 실행 테스트를 해 보았다.
하지만 실행시 OpenCV 관련 코드 실행시 에러가 발생하였다. 그래서 Visual C++ 2010 컴파일러로 직접 컴파일 한 dll 파일들 중 아래 세개 파일을 복사해 두었다.
opencv_core231.dll
opencv_highgui231.dll
opencv_imgproc231.dll
그 후로는 정상 동작을 하였다. 이제 C#으로 OpenCV를 활용한 프로그램을 만들어 봐야겠다.&
Original Post : http://neodreamer-dev.tistory.com/647
2011/10/14
C#에서 SQLite 사용하기
C#에 대해서 잘 알지는 못하고 요즘 조금 관심을 두고 있는데 C#의 데이터베이스 관련하여 모르는 상태에서 SQLite 의 예제와 관련 정보를 찾아 SQLite를 연결하여 테스트 해 보았다.
우선 C#에서 SQLite를 사용하려면 아래 사이트를 통해 개발 환경에 맞는 파일을 다운 받아야 한다.
System.Data.SQLite Download Page
내려받은 파일들 중 System.Data.SQLite.dll 와 System.Data.SQLite.Linq.dll 을 Add Reference... 를 통해 추가한다. 테스트에 사용한 코드는 아래와 같다.
C#은 C++ 에서의 방법과 많이 다른 것 같다. 효과적으로 사용하기 위해서는 C#의 데이터베이스에 대한 공부가 필요할 것 같다.&
Original Post : http://neodreamer-dev.tistory.com/595
우선 C#에서 SQLite를 사용하려면 아래 사이트를 통해 개발 환경에 맞는 파일을 다운 받아야 한다.
System.Data.SQLite Download Page
내려받은 파일들 중 System.Data.SQLite.dll 와 System.Data.SQLite.Linq.dll 을 Add Reference... 를 통해 추가한다. 테스트에 사용한 코드는 아래와 같다.
string strQuery;
textResult.Text = "Begin...\n";
SQLiteConnectionStringBuilder SQLiteConString
= new SQLiteConnectionStringBuilder();
SQLiteConString.DataSource = "test.db";
SQLiteConnection SQLite3Con
= new SQLiteConnection(SQLiteConString.ToString());
SQLite3Con.Open();
bool bPrevStepSuccess = false;
textResult.AppendText(" Try to connect with test.db ...");
if (SQLite3Con.State == ConnectionState.Open)
{
textResult.AppendText("OK\n");
// 테이블 생성
strQuery = "CREATE TABLE IF NOT EXISTS TestTable ("
+ " name VARCHAR(20)"
+ " ,age int"
+ " ,country VARCHAR(20)"
+ ")";
SQLiteCommand SQLite3Cmd = SQLite3Con.CreateCommand();
SQLite3Cmd.CommandText = strQuery;
try
{
SQLite3Cmd.ExecuteNonQuery();
textResult.AppendText(" Test Table Create ... OK\n");
bPrevStepSuccess = true;
}
catch (System.Data.SQLite.SQLiteException ex)
{
int nResult = SQLite3Con.ResultCode();
textResult.AppendText(" Test Table Create ... FAIL, Error Msg : "
+ ex.Message + "\n");
bPrevStepSuccess = false;
}
if (bPrevStepSuccess)
{
// Insert
textResult.AppendText(" Inserting ...\n");
strQuery = "INSERT INTO TestTable (name, age, country) VALUES (?,?,?);";
SQLite3Cmd.CommandText = strQuery;
SQLiteParameter paramName = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramName);
SQLiteParameter paramAge = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramAge);
SQLiteParameter paramCountry = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramCountry);
for (int i = 0; i < 10; ++i)
{
paramName.Value = "Name " + i.ToString();
paramAge.Value = 20 + i;
paramCountry.Value = "None";
int InsertRow = SQLite3Cmd.ExecuteNonQuery();
if (InsertRow == 1)
{
textResult.AppendText(" Insert ... OK\n");
}
else
{
textResult.AppendText(" Insert ... FAIL\n");
}
}
strQuery = "SELECT COUNT(*) FROM TestTable;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
using (SQLiteDataReader SQLite3Reader = SQLite3Cmd.ExecuteReader())
{
if (SQLite3Reader.Read())
{
string strRow = " Row Count ... "
+ SQLite3Reader.GetValue(0).ToString() + "\n";
textResult.AppendText(strRow);
}
}
// Selecting
textResult.AppendText(" Selecting ...\n");
strQuery = "SELECT * FROM TestTable;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
using (SQLiteDataReader SQLite3Reader = SQLite3Cmd.ExecuteReader())
{
while (SQLite3Reader.Read())
{
string strRow = " "
+ SQLite3Reader.GetValue(0).ToString() + " "
+ SQLite3Reader.GetValue(1).ToString() + " "
+ SQLite3Reader.GetValue(2).ToString()
+ "\n";
textResult.AppendText(strRow);
}
}
// Updating...
textResult.AppendText(" Updating ...\n");
strQuery = "UPDATE TestTable SET country=@country WHERE age<@age;";
SQLite3Cmd.CommandText = strQuery;
paramCountry.ParameterName = "@country";
paramCountry.Value = "KOREA";
SQLite3Cmd.Parameters.Add(paramCountry);
paramAge.ParameterName = "@age";
paramAge.Value = 25;
SQLite3Cmd.Parameters.Add(paramAge);
int nUpdated = SQLite3Cmd.ExecuteNonQuery();
string strMsg = " Updated Row(s) Count ... "
+ nUpdated.ToString() + "\n";
textResult.AppendText(strMsg);
// Deleting...
textResult.AppendText(" Deleting ...\n");
strQuery = "DELETE FROM TestTable WHERE age < @age;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
paramAge.ParameterName = "@age";
paramAge.Value = 25;
SQLite3Cmd.Parameters.Add(paramAge);
int nDeleted = SQLite3Cmd.ExecuteNonQuery();
strMsg = " Deleted Row(s) Count ... "
+ nDeleted.ToString() + "\n";
textResult.AppendText(strMsg);
// Drop Table
strQuery = "DROP TABLE IF EXISTS TestTable;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
SQLite3Cmd.ExecuteNonQuery();
textResult.AppendText(" Test Table dropped ... OK\n");
}
}
else
{
textResult.AppendText("FAIL\n");
}
SQLite3Con.Close();
textResult.AppendText("Finish.");
C#은 C++ 에서의 방법과 많이 다른 것 같다. 효과적으로 사용하기 위해서는 C#의 데이터베이스에 대한 공부가 필요할 것 같다.&
Original Post : http://neodreamer-dev.tistory.com/595
Labels:
c#
,
CSharp
,
SQLite
,
System.Data.SQLite
,
TistoryOldPost
2011/10/11
[C#] WPF App의 System Menu에 사용자 메뉴 추가하기
C#의 WPF Application 에서 System 메뉴에 사용자 메뉴를 추가하는 방법이다. 이 방법은 Add System Menu Items to WPF Window using Win32 API에서 알게된 방법으로 Form Application과 다소 다르다. Win32 API를 사용하는 것은 동일하게 보이나 메세지를 핸들링하는 부분이 다른 것 같다.
&n
Original Post : http://neodreamer-dev.tistory.com/588
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.Runtime.InteropServices;
using System.Windows.Interop;
// For Custom menu on System menu
//using System;
//using System.Windows;
//using System.Runtime.InteropServices;
//using System.Windows.Interop;
namespace MyWPFApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Win32 API Stuff
// Define the Win32 API methods we are going to use
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition,
Int32 wFlags, Int32 wIDNewItem, string lpNewItem);
/// Define our Constants we will use
public const Int32 WM_SYSCOMMAND = 0x112;
public const Int32 MF_SEPARATOR = 0x800;
public const Int32 MF_BYPOSITION = 0x400;
public const Int32 MF_STRING = 0x000;
#endregion
// The constants we'll use to identify our custom system menu items
public const Int32 _SettingsSysMenuID = 1000;
public const Int32 _AboutSysMenuID = 1001;
/// <summary>
/// This is the Win32 Interop Handle for this Window
/// </summary>
public IntPtr Handle
{
get
{
return new WindowInteropHelper(this).Handle;
}
}
public MainWindow()
{
InitializeComponent();
/// 아래 코드는 필요 없어 보임. 이벤트 핸들러가 아닌
/// 임의의 함수를 할당할 때 필요한 것으로 보임
//this.Loaded += new RoutedEventHandler(wndMain_Loaded);
}
private void wndMain_Loaded(object sender, RoutedEventArgs e)
{
/// Get the Handle for the Forms System Menu
IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false);
/// Create our new System Menu items just before the Close menu item
// Add a menu seperator
InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR,
0, string.Empty);
// Add Setting Menu
InsertMenu(systemMenuHandle, 6, MF_BYPOSITION,
_SettingsSysMenuID, "Settings...");
// Add About Menu
InsertMenu(systemMenuHandle, 7, MF_BYPOSITION,
_AboutSysMenuID, "About...");
// Attach our WndProc handler to this Window
HwndSource source = HwndSource.FromHwnd(this.Handle);
source.AddHook(new HwndSourceHook(WndProc));
}
private static IntPtr WndProc(IntPtr hwnd, int msg,
IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Check if a System Command has been executed
if (msg == WM_SYSCOMMAND)
{
/// Execute the appropriate code for
/// the System Menu item that was clicked
switch (wParam.ToInt32())
{
case _SettingsSysMenuID:
MessageBox.Show("\"Settings\" was clicked");
handled = true;
break;
case _AboutSysMenuID:
MessageBox.Show("\"About\" was clicked");
handled = true;
break;
}
}
return IntPtr.Zero;
}
}
}
실행 결과 화면
Original Post : http://neodreamer-dev.tistory.com/588
[C#] Form App 의 System Menu에 사용자 메뉴 추가하기
C#의 Windows Form Application에서 System 메뉴에 사용자 메뉴를 추가하는 방법이다. 인터넷을 통해 알게된 방법으로 Add System Menu Items to a Form using Windows API 글을 보고 알게 되었다. C# 에서의 Win32 API 사용과 메세지 핸들링에 대한 지식을 알고 있어야 겠다. C++에서는 API 사용이 쉬웠는데 그 C#에서는 다소 복잡해 보인다.
<
Original Post : http://neodreamer-dev.tistory.com/587
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.Runtime.InteropServices;
// For Custom System Menu
// using System;
// using System.Windows.Forms;
// using System.Runtime.InteropServices;
namespace MyFormApp
{
public partial class frmMain : Form
{
#region Win32 API Stuff
// Define the Win32 API methods we are going to use
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition,
Int32 wFlags, Int32 wIDNewItem, string lpNewItem);
/// Define our Constants we will use
public const Int32 WM_SYSCOMMAND = 0x112;
public const Int32 MF_SEPARATOR = 0x800;
public const Int32 MF_BYPOSITION = 0x400;
public const Int32 MF_STRING = 0x000;
#endregion
// The constants we'll use to identify our custom system menu items
public const Int32 _SettingsSysMenuID = 1000;
public const Int32 _AboutSysMenuID = 1001;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
/// Get the Handle for the Forms System Menu
IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false);
/// Create our new System Menu items just before the Close menu item
// Add a menu seperator
InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR,
0, string.Empty);
// Add Settings Menu
InsertMenu(systemMenuHandle, 6, MF_BYPOSITION,
_SettingsSysMenuID, "Settings...");
// Add About Menu
InsertMenu(systemMenuHandle, 7, MF_BYPOSITION,
_AboutSysMenuID, "About...");
}
protected override void WndProc(ref Message m)
{
// Check if a System Command has been executed
if (m.Msg == WM_SYSCOMMAND)
{
/// Execute the appropriate code for
/// the System Menu item that was clicked
switch (m.WParam.ToInt32())
{
case _SettingsSysMenuID:
MessageBox.Show("\"Settings\" was clicked");
break;
case _AboutSysMenuID:
MessageBox.Show("\"About\" was clicked");
break;
}
}
base.WndProc(ref m);
}
}
}
실행 결과 화면
Original Post : http://neodreamer-dev.tistory.com/587
Labels:
c#
,
CSharp
,
Form Programing
,
TistoryOldPost
,
폼프로그래밍
2011/09/25
[C#] Firebird Embedded로 사용하기
C#에서 Firebird를 사용해 보았는데 Embedded 도 사용이 가능한지 테스트 해 보았다.
Embedded 사용도 크게 차이가 없었다.
연결문자열의 ServerType을 1로(FbConnectionStringBuilder를 사용할 경우 csb.ServerType = FbServerType.Embedded;) 설정 하고 Firebird Embedded 패키지의 아래 파일들을 실행파일과 함께 두면 된다.
Embedded 사용도 크게 차이가 없었다.
연결문자열의 ServerType을 1로(FbConnectionStringBuilder를 사용할 경우 csb.ServerType = FbServerType.Embedded;) 설정 하고 Firebird Embedded 패키지의 아래 파일들을 실행파일과 함께 두면 된다.
fbembed.dll
firebird.conf
firebird.msg
ib_util.dll
icudt30.dll
icuin30.dll
2011/09/22
[C#] Delay
// #1 Using Thread Sleep method<
Thread.Sleep(5000);
// #2 Using TickCount
public void Delay(int ms)
{
int time = Environment.TickCount;
do
{
if(Environment.TickCount - time >= ms) return;
} while(true)
}
// #3 Using DateTime
public static DateTime PauseForMilliSeconds( int MilliSecondsToPauseFor )
{
System.DateTime ThisMoment = System.DateTime.Now;
System.TimeSpan duration = new System.TimeSpan( 0, 0, 0, 0, MilliSecondsToPauseFor );
System.DateTime AfterWards = ThisMoment.Add( duration );
while ( AfterWards >= ThisMoment )
{
System.Windows.Forms.Application.DoEvents();
ThisMoment = System.DateTime.Now;
}
return System.DateTime.Now;
}
Original Post : http://neodreamer-dev.tistory.com/578
2011/09/20
[WPF] StatusBar 프로그램 하단에 배치하기
<Window ...><
<DockPanel>
<StatusBar DockPanel.Dock="Bottom">
<StatusBarItem>
<TextBlock Name="statusText">Ready</TextBlock>
</StatusBarItem>
</StatusBar>
:
</DockPanel>
</Window>
Original Post : http://neodreamer-dev.tistory.com/576
2011/08/26
[C#] 텍스트 파일 인코딩 정보 알아내기
StreamReader reader = new StreamReader(FullPath, true);
Encoding enc = reader.CurrentEncoding;
reader.Close();
<
Original Post : http://neodreamer-dev.tistory.com/568
[C#] 간단하게 텍스트 파일 읽고 쓰기
//File 객체를 이용한 텍스트 파일 읽고 쓰기
string strContent = File.ReadAllText(path);
File.WriteAllText(path, strContent);
// Stream을 이용한 텍스트 파일 읽고 쓰기
StreamReader reader = new StreamReader(itemFile.FullPath, true);
string strContent = reader.ReadToEnd();
reader.Close();
StreamWriter writer = new StreamWriter(path);
writer.Write(strContent);
writer.Close();
<
Original Post : http://neodreamer-dev.tistory.com/567
Labels:
c#
,
File Object
,
StreamReader
,
TextFile
,
TistoryOldPost
2011/08/19
[C#] XML 다루는 간단한 소스
C#을 공부하면서 XML 다루게 되면서 알게된 내용으로 기록용으로 정리해 보았다.
아래 소스는 간단하게 XML 데이터를 저장하고 읽어들이는 소스이다.
XmlDocument 나 XmlNode Class 에는 위의 코드에서 사용한 것 보다 더 많은 기능을 갖고 있다. 자세한 기능들에 대해서는 따로 공부를 해 봐야 겠다.
&
Original Post : http://neodreamer-dev.tistory.com/566
아래 소스는 간단하게 XML 데이터를 저장하고 읽어들이는 소스이다.
// Writting
XmlDocument xmlDoc = new XmlDocument();
XmlNode nodeItems = xmlDoc.CreateNode("element", "Items", "");
foreach (ListViewItem item in ListView.Items)
{
XmlNode nodeItem = xmlDoc.CreateNode("element", "Item", "");
XmlNode nodeFind = xmlDoc.CreateNode("element", "Find", "");
nodeFind.InnerText = "...";
XmlNode nodeReplace = xmlDoc.CreateNode("element", "Replace", "");
nodeReplace.InnerText = "...";
nodeItem.AppendChild(nodeFind);
nodeItem.AppendChild(nodeReplace);
nodeItems.AppendChild(nodeItem);
}
xmlDoc.AppendChild(nodeItems);
xmlDoc.Save(saveFileDialog.FileName);
<Items>
<Item>
<Find>a1</Find>
<Replace>b1</Replace>
</Item>
<Item>
<Find>a2</Find>
<Replace>b2</Replace>
</Item>
</Items>
// Reading
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(openFileDialog.FileName);
XmlNode nodeItems = xmlDoc.FirstChild;
foreach (XmlNode nodeItem in nodeItems)
{
string strFind = nodeItem.FirstChild.InnerText;
string strReplace = nodeItem.LastChild.InnerText;
}
XmlDocument 나 XmlNode Class 에는 위의 코드에서 사용한 것 보다 더 많은 기능을 갖고 있다. 자세한 기능들에 대해서는 따로 공부를 해 봐야 겠다.
&
Original Post : http://neodreamer-dev.tistory.com/566
2011/08/04
[C#] Thread 에서 간단하게 UI 제어하기
C#을 보고 있던 중 Thread 에서 UI를 제어하는 부분에서 막혀 정보를 찾다가 간단하게 제어하는 방법을 찾았다.
this.Invoke(new MethodInvoker(delegate() {<
// UI 제어 코드
}));
Original Post : http://neodreamer-dev.tistory.com/560
2011/08/01
요긴한 Tag
요즘 C#에 대한 맛보기 공부를 하고 있는데 C#에도 Tag Property가 있었다. Tag Property 는 Delphi 나 C++ Builder를 다룰 때 요긴하게 사용하던 것으로 Delphi나 C++ Builder 에서는 32비트 int 형으로 선언되어 있어 정수형 자료와 포인터를 저장하고 관리할 수 있었다.
실제로 Tag Property 에 대해서 VCL 문서상에서도 아래와 같이 개발자를 위해 제공하는 것으로 명시되어 있다.
Stores an integer value as part of a component.
Tag has no predefined meaning. The Tag property is provided for the convenience of developers. It can be used for storing an additional integer value or it can be typecast to any 32-bit value such as a component reference or a pointer.
Classes.TComponent.Tag
http://docwiki.embarcadero.com/VCL/en/Classes.TComponent.Tag
C#을 보면서 Tag에 대한 존재를 확인하였다.
C#의 언어적 특성때문인지 C#에서는 Tag가 Object로 선언 되어 있었다. C#의 Object에서 파생되는 모든 것을 담을 수 있다. 그래서 문자열도 쉽게 저장할 수 있다. VCL 의 Tag 보다 확장된 것이다.
Any type derived from the Object class can be assigned to this property. If the Tag property is set through the Windows Forms designer, only text can be assigned.
A common use for the Tag property is to store data that is closely associated with the control. For example, if you have a control that displays information about a customer, you might store a DataSet that contains the customer's order history in that control's Tag property so the data can be accessed quickly.
Control.Tag Property
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag.aspx
<
Original Post : http://neodreamer-dev.tistory.com/559
실제로 Tag Property 에 대해서 VCL 문서상에서도 아래와 같이 개발자를 위해 제공하는 것으로 명시되어 있다.
Stores an integer value as part of a component.
Tag has no predefined meaning. The Tag property is provided for the convenience of developers. It can be used for storing an additional integer value or it can be typecast to any 32-bit value such as a component reference or a pointer.
Classes.TComponent.Tag
http://docwiki.embarcadero.com/VCL/en/Classes.TComponent.Tag
C#을 보면서 Tag에 대한 존재를 확인하였다.
C#의 언어적 특성때문인지 C#에서는 Tag가 Object로 선언 되어 있었다. C#의 Object에서 파생되는 모든 것을 담을 수 있다. 그래서 문자열도 쉽게 저장할 수 있다. VCL 의 Tag 보다 확장된 것이다.
Any type derived from the Object class can be assigned to this property. If the Tag property is set through the Windows Forms designer, only text can be assigned.
A common use for the Tag property is to store data that is closely associated with the control. For example, if you have a control that displays information about a customer, you might store a DataSet that contains the customer's order history in that control's Tag property so the data can be accessed quickly.
private void buttonNewCustomer_Click(object sender, EventArgs e)
{
/* Create a new customer form and assign a new
* Customer object to the Tag property. */
CustomerForm customerForm = new CustomerForm();
customerForm.Tag = new Customer();
customerForm.Show();
}
Control.Tag Property
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag.aspx
<
Original Post : http://neodreamer-dev.tistory.com/559
Labels:
c#
,
C++ Builder
,
Delphi
,
Tag Property
,
TistoryOldPost
,
VCL
2011/07/28
[C#] Form 디자이너 클래스는 가장 먼저 선언 되어야 하네...
메인 폼의 클래스 위에 습관처럼 다른 클래스는 선언 하였다. 그리고 Form 디자인 창을 열었더니 아래와 같은 에러 메시지를 만났다.
"The class frmMain can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again."
C++에서의 습관으로 메인 클래스 위에 다른 작은 구조체나 클래스를 선언하여 사용하였는데 Windows Form을 사용하는 C# 프로그래밍에서는 Visual Studio에서 지원하는 디자이너를 사용하려면 그렇게 사용할 수가 없다. 좀 불편
Original Post : http://neodreamer-dev.tistory.com/558
"The class frmMain can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again."
C++에서의 습관으로 메인 클래스 위에 다른 작은 구조체나 클래스를 선언하여 사용하였는데 Windows Form을 사용하는 C# 프로그래밍에서는 Visual Studio에서 지원하는 디자이너를 사용하려면 그렇게 사용할 수가 없다. 좀 불편
Original Post : http://neodreamer-dev.tistory.com/558
[C#] 경로 요소 분리하기
C++ 에는 _splitpath 라는 멋진 함수가 있어서 전체 경로에서 구성 요소(드라이브, 패스, 파일명, 확장자)를 분리할 수 있었다.
C#에서 이용할 수 있는 함수가 있나 찾아 보았는데 함수는 없고 보다 많은 기능을 포함하고 있는 객체를 찾았다.
System.IO.Path 인데 이 녀석은 경로에 관련한 많은 기능을 담고 있다.
아래 코드는 MSDN에서 발췌해 온 예제 코드 이다.
public static void Main()
{
string path1 = @"c: emp\MyTest.txt";
string path2 = @"c: emp\MyTest";
string path3 = @"temp";
if (Path.HasExtension(path1))
{
Console.WriteLine("{0} has an extension.", path1);
}
if (!Path.HasExtension(path2))
{
Console.WriteLine("{0} has no extension.", path2);
}
if (!Path.IsPathRooted(path3))
{
Console.WriteLine("The string {0} contains no root information.", path3);
}
Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3));
Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath());
Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName());
/* This code produces output similar to the following:
* c: emp\MyTest.txt has an extension.
* c: emp\MyTest has no extension.
* The string temp contains no root information.
* The full path of temp is D:\Documents and Settings\cliffc\...\Debug emp.
* D:\Documents and Settings\cliffc\Local Settings\Temp...\ is the location for temporary files.
* D:\Documents and Settings\cliffc\Local Settings\Temp... temp3D.tmp is a file available for use.
*/
}
MSDN의 Path 클래스 설명 페이지 <
Original Post : http://neodreamer-dev.tistory.com/557
Labels:
_splitpath
,
c#
,
CSharp
,
Path Class
,
System.IO.Path
,
TistoryOldPost
[C#] Drag&Drop 으로 파일 받기
특정 컨트롤에서 Drag&Drop 으로 파일을 받으려면 우선 해당 컨트롤의 AllowDrop 옵션을 True로 설정한다.
그리고 컨트롤의 DragOver 와 DragDrop 이벤트 핸들러를 작성한다.
아래 코드는 간단하게 구현 해본 Drag&Drop 이다.
private void lvFiles_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.All;
}
private void lvFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
for (int i = 0; i < files.Count(); ++i)
{
lvFiles.Items.Add(files[i]);
}
string strMsg = files.Count().ToString() + " File(s) dropped!!";
MessageBox.Show(strMsg);
}
<
Original Post : http://neodreamer-dev.tistory.com/555
Labels:
c#
,
CSharp
,
Drag&Drop
,
DragOver
,
TistoryOldPost
2011/07/27
Editplus에 C# 설정하기
C#을 잠깐 보면서 어는 서적이든 처음에 Console 프로그래밍에 대해서 언급을 하고 있는데 이 때문에 덩치큰 Visual Studio를 실행하는 것이 싫어 일반 편집기에서 하는 방법을 알아보았다. 물론 명령줄을 이용하면 되는데 조금 편리하게 사용하기 위해 편집기 옵션을 이용하였다.
Editplus 의 사용자 툴을 등록하고 사용하므로써 편하게 컴파일과 실행을 할 수 있다.
아래 두 툴 설정을 추가하면 된다.
Menu Text: C# Compile
Command: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe
Argument: $(FileName)
Initial Directory: $(FileDir)
Menu Text: C# Run
Command: cmd
Argument: /c $(FileNameNoExt)
Initial Directory: $(FileDir)
위와 같이 설정하면 다른 설정이 없을 경우 Ctrl + 1과 Ctrl + 2로 할당된다.
설정을 마치고 C# 파일을 생성하고 아래와 같은 코드를 입력하였다.
코드를 작성하고 Ctrl + 1로 컴파일하고 Ctrl + 2로 실행을하면 간단한 C# 프로그램을 테스트할 수 있다.
<
Original Post : http://neodreamer-dev.tistory.com/553
Editplus 의 사용자 툴을 등록하고 사용하므로써 편하게 컴파일과 실행을 할 수 있다.
아래 두 툴 설정을 추가하면 된다.
Menu Text: C# Compile
Command: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe
Argument: $(FileName)
Initial Directory: $(FileDir)
Menu Text: C# Run
Command: cmd
Argument: /c $(FileNameNoExt)
Initial Directory: $(FileDir)
위와 같이 설정하면 다른 설정이 없을 경우 Ctrl + 1과 Ctrl + 2로 할당된다.
설정을 마치고 C# 파일을 생성하고 아래와 같은 코드를 입력하였다.
using System;
class MyCSharpApp
{
public static void Main()
{
Console.WriteLine("Hello! C# World");
}
}
코드를 작성하고 Ctrl + 1로 컴파일하고 Ctrl + 2로 실행을하면 간단한 C# 프로그램을 테스트할 수 있다.
<
Original Post : http://neodreamer-dev.tistory.com/553
Subscribe to:
Posts
(
Atom
)