namespace WindowsFormsApplication5
{
    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.Drawing.Drawing2D;

    /// <summary>
    /// Main application form
    /// </summary>
    public partial class Form1 : Form
    {
        /// <summary>
        /// Initializes a new instance of the WindowsFormsApplication5.Form1 class
        /// </summary>
        public Form1() {
            InitializeComponent();
            DoubleBuffered = true;
        }

        private Point selectionStart;
        private Point selectionEnd;
        private Rectangle selection;
        private bool mouseDown;

        private void GetSelectedTextBoxes() {
            List<TextBox> selected = new List<TextBox>();

            foreach (Control c in Controls) {
                if (c is TextBox) {
                    if (selection.IntersectsWith(c.Bounds)) {
                        selected.Add((TextBox)c);
                    }
                }
            }

            // Replace with your input box
            MessageBox.Show("You selected " + selected.Count + " textbox controls.");
        }

        protected override void OnMouseDown(MouseEventArgs e) {
            selectionStart = PointToClient(MousePosition);
            mouseDown = true;
        }

        protected override void OnMouseUp(MouseEventArgs e) {
            mouseDown = false;

            SetSelectionRect();
            Invalidate();

            GetSelectedTextBoxes();
        }

        protected override void OnMouseMove(MouseEventArgs e) {
            if (!mouseDown) {
                return;
            }

            selectionEnd = PointToClient(MousePosition);
            SetSelectionRect();

            Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e) {
            base.OnPaint(e);

            if (mouseDown) {
                using (Pen pen = new Pen(Color.Black, 1F)) {
                    pen.DashStyle = DashStyle.Dash;
                    e.Graphics.DrawRectangle(pen, selection);
                }
            }
        }

        private void SetSelectionRect() {
            int x, y;
            int width, height;

            x = selectionStart.X > selectionEnd.X ? selectionEnd.X : selectionStart.X;
            y = selectionStart.Y > selectionEnd.Y ? selectionEnd.Y : selectionStart.Y;

            width = selectionStart.X > selectionEnd.X ? selectionStart.X - selectionEnd.X : selectionEnd.X - selectionStart.X;
            height = selectionStart.Y > selectionEnd.Y ? selectionStart.Y - selectionEnd.Y : selectionEnd.Y - selectionStart.Y;

            selection = new Rectangle(x, y, width, height);
        }
    }
}

 

Posted by 모과이IT
,

DLL 프로젝트에서 종속된 DLL들을 로드를 할때 프로그래밍적으로 종속된 DLL의 path를 변경해야될

경우가 있었다. 아래 코드는 프로그래밍적으로 종속된 DLL들의 path를 변경해준다



public void test()

{

AppDomain currentDomain = AppDomain.CurrentDomain;

currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

}


private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)

{

    //This handler is called only when the common language runtime tries to bind to the assembly and fails.


    //Retrieve the list of referenced assemblies in an array of AssemblyName.

    Assembly MyAssembly, objExecutingAssembly;

    string strTempAssmbPath = "";


    objExecutingAssembly = Assembly.GetExecutingAssembly();

    AssemblyName[] arrReferencedAssmbNames = objExecutingAssembly.GetReferencedAssemblies();


    //Loop through the array of referenced assembly names.

    foreach(AssemblyName strAssmbName in arrReferencedAssmbNames)

    {

        //Check for the assembly names that have raised the "AssemblyResolve" event.

        if(strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(",")))

        {

            //Build the path of the assembly from where it has to be loaded.                

            strTempAssmbPath = "C:\\Myassemblies\\" + args.Name.Substring(0,args.Name.IndexOf(","))+".dll";

            break;

        }


    }


    //Load the assembly from the specified path.                    

    MyAssembly = Assembly.LoadFrom(strTempAssmbPath);                   


    //Return the loaded assembly.

    return MyAssembly;          

}


[참고자료]

http://stackoverflow.com/questions/1373100/how-to-add-folder-to-assembly-search-path-at-runtime-in-net


Posted by 모과이IT
,

☞ C# 클래스라이브러리 프로젝트 생성 - ComPlusExample

 



 

☞ System.EnterpriseSevices 참조추가

 



 

 

☞ AssemblyInfo.cs 수정 ( Properties 폴더에 있음 )

[assembly: ComVisible(false)] 를 [assembly: ComVisible(true)]로 변경

 

☞ ComPlusClass 클래스 파일추가

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.EnterpriseServices;
[assembly: ApplicationName("ComPlusExample")]
[assembly: Description("Complus Assembly")]
[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ApplicationAccessControl(false)]

namespace ComPlusExample
{
    [EventTrackingEnabled(true)]
    [Description("Interface Serviced Component")]
    public class ComPlusClass : ServicedComponent
    {
        public string Base64Encode(string str)
        {
            byte[] byt = System.Text.Encoding.UTF8.GetBytes(str);

            return Convert.ToBase64String(byt);
        }

        public string Base64Decode(string str)
        {
            byte[] byt = Convert.FromBase64String(str);

            return System.Text.Encoding.UTF8.GetString(byt);
        }
    }
}

 

☞  강력한 이름 키 만들기(프로젝트 오른클릭 속성클릭)

- 서명탭 -> 어셈블리 서명 체크 -> 새로만들기

 



 

- 키 파일 이름 : ComPlusExample -> 체크박스 해제 -> 확인

 



 



 

☞ Visual Studio 2008 명령 프롬프트를 이용한 등록

- 빌드후 dll이 있는 곳에서 등록 (프로젝트경로\bin\Debug\ComPlusExample.dll)

regsvcs ComPlusExample.dll
regasm ComPlusExample.dll

☞ COM+ 응용 프로그램 등록확인

 

 

☞ test.asp 실행

<%

set Com = server.createobject("ComPlusExample.ComPlusClass")
encodeStr = Com.Base64Encode("홍길동")
Response.Write "암호화 : " & encodeStr & "<br/>"
Response.Write "복호화 : " & Com.Base64Decode(encodeStr) & "<br/>"

%>
 

☞ 결과

 

 

 

출처

http://blog.naver.com/whwlfnsl?Redirect=Log&logNo=70112831675


Posted by 모과이IT
,

COM+ component를 만들어서 등록된 이후에 웹서비스에서 멀티쓰레딩으로 실행 하기위해서는 IIS(인터넷 정보서비스)관리자에서 설정이 필요하다

(설정을 하지 않고 실행하게 되면 동기적으로 실행되고 비동기적으로 실행이 되질 않습니다. 한마디로 순차적으로 진행된다)





DefaultAppPool을 선택하여 [고급설정]을 클릭한다.







"최대 작업자 프로세스 수"를 적절히 셋팅해 준다 기본적으로 1로 되어져있다. 1이상으로 해주어야한다.

그리고 "32비트 응용 프로그램 사용"에서도 TRUE로 체크를 해주어야지 COM+가 정상실행이 된다







작업관리자에 보면 ISS Worker Process로 인해서 멀티쓰레딩으로 실행이 되는것을 확인할수 있다


'개발지식창고 > C#' 카테고리의 다른 글

ClassLibrary 프로젝트에서 종속 DLL path 변경법  (0) 2015.03.01
COM+ 생성방법  (0) 2015.02.25
.net Framework Error (HRESULT 0x8007000B)  (0) 2015.02.11
C#에서 DebugView 사용하기  (0) 2015.02.02
C# MultiMedia API in MSDN  (0) 2015.01.31
Posted by 모과이IT
,




Project Properties -> Build -> Platform target -> x86 may solved this problem.




[참고 사이트]

http://stackoverflow.com/questions/18007967/net-framework-error-hresult-0x8007000b





'개발지식창고 > C#' 카테고리의 다른 글

COM+ 생성방법  (0) 2015.02.25
COM+ 컴포넌트 멀티쓰레드 실행을 위한 IIS설정  (0) 2015.02.14
C#에서 DebugView 사용하기  (0) 2015.02.02
C# MultiMedia API in MSDN  (0) 2015.01.31
ftp, http Up,DownLoad 방법  (0) 2013.03.15
Posted by 모과이IT
,

자료출처  http://yegam400.tistory.com/395

 

C#에서 OutputDebugString을 할려면 다음과 같은 2가지 방법이 있다.

Debug.Write(), Trace.Write()의 차이점은 Debug는 Debug모드 빌드에서만 동작하며, Trace는 Release/Debug 둘다 동작한다는 점이다. 물론 OutputDebugString기반이므로 DebugView에서도 확인할 수 있다.

 

System.Diagnostics.Debug.Write("Debug1");

System.Diagnostics.Debug.Write("Debug2");

System.Diagnostics.Trace.Write("Trace1");

System.Diagnostics.Trace.Write("Trace2"); 

 

자료출처  http://www.go4expert.com/forums/showthread.php?t=2061

 

System.Diagnostics.Debug.WriteLine("I am using dot net debugging");
System.Diagnostics.Trace.WriteLine("I am using dot net tracing");


Posted by 모과이IT
,

https://msdn.microsoft.com/en-us/library/aa970915(v=vs.110).aspx#mediaapi

'개발지식창고 > C#' 카테고리의 다른 글

.net Framework Error (HRESULT 0x8007000B)  (0) 2015.02.11
C#에서 DebugView 사용하기  (0) 2015.02.02
ftp, http Up,DownLoad 방법  (0) 2013.03.15
ToolStrip Docking Move  (0) 2013.02.21
C++로 만든 DLL 을 C#에서 사용하기  (0) 2013.01.03
Posted by 모과이IT
,

현재 프로젝트에서 응용프로그램이 2개가 있는데 한쪽에서는 ftp로 Upload를 하고

다른 한쪽에 프로그램에서 그 Upload된 파일을 http 방식으로 받아와야 하는 로직이기때문에 아래에

ftp Upload와 http Download하는 방법에 대한 예제소스.

 

[ftp] - Upload

FileInfo fInfo = new FileInfo("d:\\스타크래프트.zip");
this.progressBar = progressBar;

            fileSize = fInfo.Length;
            System.Diagnostics.Debug.Write("FileSize => " + fileSize.ToString());
            WebClient wc = new WebClient();
            wc.Credentials = new NetworkCredential("ftp계정id", "ftp계정암호")
            wc.UploadProgressChanged += new UploadProgressChangedEventHandler(request_DownloadProgressChanged);
            wc.UploadFileCompleted += new UploadFileCompletedEventHandler(request_DownloadFileCompleted);     // 메시지 핸들러 추가

            Uri ftpUri = new Uri("ftp://192.168.0.56:21/book/스타크래프트.zip");
            wc.UploadFileAsync(ftpUri,"d:\\스타크래프트.zip");

 

 

[http] - DownLoad

웹서버상에서 파일을 자신의 컴퓨터에 저장할 때.
;

System.Net;        //WebClient클래스를 위한 네임스페이스

WebClient WClient = new WebClient();
WClient.DownloadFile("다운로드 URL", "저장할 로컬 경로 및 파일명");
 

ex) WClient.DownloadFile(http://000.000.000.0/ddd.jpg, "c:\dddd.jpg");

저작자 표시

'개발지식창고 > C#' 카테고리의 다른 글

C#에서 DebugView 사용하기  (0) 2015.02.02
C# MultiMedia API in MSDN  (0) 2015.01.31
ToolStrip Docking Move  (0) 2013.02.21
C++로 만든 DLL 을 C#에서 사용하기  (0) 2013.01.03
Serialize an ArrayList object to a binary file  (0) 2012.12.24
Posted by 모과이IT
,

private void tsBtnRight_Click(object sender, EventArgs e)

{

    //ToolContainer 오른쪽패널에 ToolStrip을 위치 시킵니다.

    tcMain.RightToolStripPanel.Controls.Add(tsMenu);

}

private void tsBtnLeft_Click(object sender, EventArgs e)

{

    //ToolContainer 왼쪽패널에ToolStrip을 위치 시킵니다.

    tcMain.LeftToolStripPanel.Controls.Add(tsMenu);

}

private void tsBtnTop_Click(object sender, EventArgs e)

{

    //ToolContainer 윗쪽패널에 ToolStrip을 위치 시킵니다.

    tcMain.TopToolStripPanel.Controls.Add(tsMenu);

}

private void tsBtnBottom_Click(object sender, EventArgs e)

{

    //ToolContainer 아랫쪽패널에 ToolStrip을 위치 시킵니다.

    tcMain.BottomToolStripPanel.Controls.Add(tsMenu);

}

'개발지식창고 > C#' 카테고리의 다른 글

C# MultiMedia API in MSDN  (0) 2015.01.31
ftp, http Up,DownLoad 방법  (0) 2013.03.15
C++로 만든 DLL 을 C#에서 사용하기  (0) 2013.01.03
Serialize an ArrayList object to a binary file  (0) 2012.12.24
C# 관련 추천사이트  (0) 2012.12.04
Posted by 모과이IT
,

출처 : http://dal2iya.tistory.com/136

 

 

1. C++로 코드 작성하기

 1) 코드 바로 작성하기 예제

 #include <stdio.h>

extern "C"
{
  __declspec(dllexport) void DisplayHelloFromDLL()
  {

    // 여기에 내용내용내용
    printf ("Hello from DLL !\n");
  }
}

 2) 선언과 정의를 따로 분리하실경우, 선언은 다음과 같이

 extern "C" __declspec(dllimport) void Start_DebugView();

 

2. C++ 프로젝트 Property Setting


먼저 , C++로 만든 프로젝트에서 다음과 같이 설정을 해 줍니다. (꼭)

다음과 같이 설정해주시지 않으면, C#에서 DLL을 Import하여도 실제로 Lo

출처 : 훈스닷넷, 밑에 참고 참고
ad가 되지 않습니다...
(그러면 삽질을 하게되요... ... 누구처럼??)

 

 

3. C#에서 사용하기

C++로 만든 dll은 기존의 C#의 dll을 사용하던 것 처럼 reference에 추가해서 사용하실 수 없습니다.
그래서 코드에 직접 , 사용한다고 선언해주고 사용하여야 합니다.

먼저, C++을 이용해서 만든 dll을 필요한 위치에 위치 시킵니다. 저같은 경우 실행파일과 같은 위치에 위치하였습니다. (*)
그런 뒤 ,

1 ) using System.Runtime.InteropServices;    NameSpace를 추가한 후
2 ) [DllImport("TestLib.dll")] 를 이용하여 사용할 Dll을 명시한 후 사용할 함수를 선언합니다.
(* 실행파일과 같은 위치에 있으면 dll의 이름만 쓰시면 됩니다. 아닌경우 주소까지 같이 명시)
3) 그리고 그냥 함수처럼 사용하시면 됩니다.

 using System;
using System.Runtime.InteropServices;     // DLL support

class HelloWorld
{
    [DllImport("TestLib.dll")]
    public static extern void DisplayHelloFromDLL ();

    static void Main ()
    {
        Console.WriteLine ("This is C# program");
        DisplayHelloFromDLL ();
    }
}

 

 

* 줏은 Tip

이래저래 귀찮다.. 하시면 
엔진은 CLR을 사용하지 않고 Native Code로 컴파일하고 엔진을 Wrapping 하는 CLR C++ 프로젝트를 하나 더 만들고,
 그 프로젝트를 참조하여 C#에서 사용하는 방법이 있습니다.
주의 ) 어쩌면 더 귀찮아 지실수도... 있습니다.
* 하지만 약간의 디버깅이 가능하고, 밑의 파라미터 관련하여 포팅도 가능합니다!!!

 

 

* 한 가지 추가

 C++에서 사용하는 클래스와, C#에서 사용하는 클래스가 다르기 때문에, 파라미터 사용에 대해서 약간의 포팅이 필요합니다.
예를들면 다음과 같습니다.

 1) C++ 선언

  HWND FindWindow(LPCSTR swClassName, LPCSTR swTitle);

2) C# 선언

 [DllImport(“user32.dll”)]     public static extern int FindWindow(string a, string b);

 설명 )

HWND는 윈도우 핸들을 표현하는 32비트 정수 이므로, int형으로 치환되고 LPCSTR 형은 NULL로 끝나는 문자열을 표현합니다.

이때 PInvoke string을 자동으로 LPCSTR로 치환해 주는 역할을 하게 됩니다.

 

WIN32 데이터형의 치환

Win32 API에서 일반적으로 사용하고 있는 데이터형은 모두 C#의 데이터 형으로 치환될 수 있습니다.

 

Win32 API TYPE

C#

BOOL, BOOLEAN

bool

BYTE

byte

CALLBACK

delegate

COLORREF

int

DWORD

int

DWORD_PTR

long

DWORD32

uint

DWORD64

ulong

FLOAT

float

HACCEL

int

HANDLE

int

HBITMAP

int

HBRUSH

int

HCONV

int

(모든 HANDLE 타입) Hxxxx

int

LPARAM

long

LPCSTR

[in] string [out] StringBuilder

LPBOOL

ref bool

이외 LP*

ref 형식

UINT

uint

Uxxxx

unsigned 타입들..

WORD

Short

WPARAM

Uint

 

단, String의 경우는 인코딩과 관련하여 약간 까다롭습니다..
C++의 경우 char가 1byte, C#의 경우 char가 2byte이기 때문에 ,,,,
위에서 LPCSTR 가 [in] string [out] StringBuilder와 바로 호환이 된다고해서 좋다고 사용하였다가, 인코딩이 다 깨져서 낭패를 봤습니다..... ㅠ_ㅠ (거짓말쟁이)

이 경우는 다음과 같이 해결하였습니다.

 

1) C++ 선언

  extern "C" __declspec(dllexport) void Save_DebugView_Path(char* Save_Path);

 2) C# 선언

 [DllImport("OutputDebugString_HookingDll.dll")]  
 public static extern void Save_DebugView_Path([System.Runtime.InteropServices.InAttribute()]
            [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string
pFileName);

 

다음과 같이 사용하면,
(한글을 사용하지 않는 이상) 글자가 깨지지 않고 잘 전달되는 모습을 확인하실 수 있습니다..
Attribute에서 명시적으로 String에 대해 LPWStr로 변환해서 넘겨주도록 지정하고 있기 때문이에요.
아래와 같은 과정이 자동으로 수행된다 생각하셔도 되겠습니다.
  

  string Path = @"c:\test.txt";
IntPtr PathPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(Path);
// ~~~~~~~~~~~~~~~~~~~~
//Char *PathPointer = (Char*)PathPtr.ToPointer();
// ~~~~~~~~~~~~~~~~~~~~
System.Runtime.InteropServices.Marshal.FreeHGlobal(PathPtr);

... 네 그렇습니다..

그 외의 특별한 경우는 밑에 참고를 잘 뒤져보시면 몇몇개 나옵니다.. 될지안될지는 못믿겠습니다...ㅠㅠ(위에서 한개 안되니까 ... 장담하긴어렵네요..)

 

이상으로 마칩니다. 감사합니다.

 

참고)

http://snipplr.com/view/12509/pass-a-string-from-c-to-a-c-dll-in-net-and-get-a-pointer-to-the-strings-chars/

http://www.codeproject.com/KB/cs/usecdlllibincs.aspx
http://www.mdfo.kr/tag/UnmanagedType
http://sonic.tistory.com/entry/CC%EB%A1%9C-%EB%A7%8C%EB%93%A0-DLL-Library%EB%A5%BC-C%EC%97%90%EC%84%9C-%EC%93%B0%EA%B8%B0

http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=17&MAEULNO=8&no=113249&ref=113249&page=31

http://hoons.kr/Board.aspx?Name=QACSHAP&Mode=2&BoardIdx=24982&Key=&Value=
http://www.hoons.kr/Board.aspx?Name=cshaptip&Mode=2&BoardIdx=21751&Key=&Value=
http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=1040102&docId=67700148&qb=U3RydWN0TGF5b3V0


 

'개발지식창고 > C#' 카테고리의 다른 글

ftp, http Up,DownLoad 방법  (0) 2013.03.15
ToolStrip Docking Move  (0) 2013.02.21
Serialize an ArrayList object to a binary file  (0) 2012.12.24
C# 관련 추천사이트  (0) 2012.12.04
Form 이벤트  (0) 2012.11.30
Posted by 모과이IT
,