'Computer Science' 카테고리의 다른 글
| JSP 기초 강좌 사이트 (0) | 2009.04.22 |
|---|---|
| php 그래프 그리기 (0) | 2009.04.22 |
| Writing Data CDs (0) | 2009.04.22 |
| 파이썬으로 하는 웹 클라이언트 프로그래밍 (0) | 2009.04.22 |
| TCP/IP 소켓 프로그래밍 with C# (0) | 2009.04.22 |
| JSP 기초 강좌 사이트 (0) | 2009.04.22 |
|---|---|
| php 그래프 그리기 (0) | 2009.04.22 |
| Writing Data CDs (0) | 2009.04.22 |
| 파이썬으로 하는 웹 클라이언트 프로그래밍 (0) | 2009.04.22 |
| TCP/IP 소켓 프로그래밍 with C# (0) | 2009.04.22 |
출처 : http://www.vbaccelerator.com/home/net/code/Libraries/Writing_CDs/Writing_Data_CDs/article.asp
This article demonstrates how to use the IMAPI wrapper to burn data CDs (also known as "Joliet" format CDs). Sample code is provided in both C# and VB.
Before you begin, note that this sample uses the IMAPI Wrapper for the CD burning functions. To run the sample, you will need to have acclImapiWrapper.DLL registered in the Global Assembly cache (GAC). If you place the DLL next to the executable in your Debug or Release directory then you will also be able to run (but you may need to change the project references to run in VS.NET).
Recording a data CD using IMAPI involves performing the following steps:
During the last step, the DiscMaster will raise a number of events describing progress as the disc is staged or burnt, and also allows the burn to be cancelled.
I'll describe these steps briefly with VB.NET code examples. The C# code is very similar; refer to the downloads for details.
The only directly instantiable class in the IMAPI Wrapper is the DiscMaster object, from which all other classes can be obtained. This can be declared WithEvents in VB because you'll want to catch the progress and cancel events. Next, the recording mode is set by obtaining a JolietDiscMaster object. A reference to the returned object is kept as this is needed to stage the image (calling the JolietDiscMaster() again will result in a new instance being returned). Having done that, the list of recorders is populated into a ComboBox and the selected index set.
Private WithEvents discMaster As discMaster = Nothing Private jolietDiscMaster As JolietDiscMaster = Nothing Private Sub GetRecorders() Dim ex As Exception Try discMaster = New DiscMaster() jolietDiscMaster = discMaster.JolietDiscMaster() Dim recorder As DiscRecorder For Each recorder In discMaster.DiscRecorders cboRecorder.Items.Add( _ New ComboRecorderWrapper(recorder)) Next If (cboRecorder.Items.Count > 0) Then cboRecorder.SelectedIndex = 0 End If Catch ex MessageBox.Show( _ Me, String.Format("Unable to initialise the IMAPI library {0}", ex), _ Text, MessageBoxButtons.OK, MessageBoxIcon.Stop) If Not (discMaster Is Nothing) Then discMaster.Dispose() End If End Try End Sub Private Sub cboRecorder_SelectedIndexChanged( _ ByVal sender As Object, _ ByVal e As System.EventArgs _ ) Handles cboRecorder.SelectedIndexChanged If (cboRecorder.SelectedIndex > -1) Then Dim wrapper As ComboRecorderWrapper = cboRecorder.SelectedItem discMaster.DiscRecorders.ActiveDiscRecorder = wrapper.DiscRecorder End If End SubAs noted in the IMAPI Wrapper article, you must ensure that the Dispose method is called on the DiscMaster instance before ending your application. Failure to do this will result in any subsequent attempt to access the library failing with a "Stash In Use" error. To ensure this occurs, I've included an Application ThreadException handler, which is called in the unfortunate event of an untrapped exception in the code:
Public Sub New() ' ... 'Add any initialization after the InitializeComponent() call AddHandler Application.ThreadException, AddressOf application_ThreadException Show() Refresh() GetRecorders() End Sub Private Sub application_ThreadException( _ ByVal sender As Object, _ ByVal e As ThreadExceptionEventArgs) MessageBox.Show(Me, _ String.Format("An untrapped exception occurred: {0}.", _ e.Exception), _ Text, MessageBoxButtons.OK, MessageBoxIcon.Error) Close() End Sub Protected Overrides Sub OnClosing( _ ByVal e As System.ComponentModel.CancelEventArgs) ' .... '// Clear up: MyBase.OnClosing(e) Cursor.Current = Cursors.WaitCursor sbrMain.Text = "Closing IMAPI interface..." jolietDiscMaster.Dispose() discMaster.Dispose() Cursor.Current = Cursors.Default End SubIn this sample I'm exposing the stack trace of the exception directly; in a real application this would be bad practice and really the exception should be logged and a more descriptive message shown.
The JolietDiscMaster instance exposes a RootStorage property, which returns a JolietDiscMasterStorage instance representing the root directory of the CD. You can add files and/or sub-directories to this object; sub-directories are also represented as JolietDiscMasterStorage objects. When adding a file, you specify the path of the file to copy from on disc and the name of the file in the directory to write it out to. Sub-directories just have a name. For the purposes of the sample, I just allow a directory to be added and optionally recursed:
''' <summary> ''' Adds a directory to the storage, optionally including ''' any subdirectories. ''' </summary> ''' <param name="path">Path to the directory to add</param> ''' <param name="recurse"><c>true</c> to include subdirectories, ''' <c>false</c> otherwise.</param> Public Sub AddDirectory(ByVal path As String, ByVal recurse As Boolean) Dim storage As JolietDiscMasterStorage = jolietDiscMaster.RootStorage AddFilesToStorage(storage, path, recurse) End Sub Private Sub AddFilesToStorage( _ ByVal storage As JolietDiscMasterStorage, _ ByVal startPath As String, _ ByVal recurse As Boolean) If (recurse) Then Dim dir As String For Each dir In Directory.GetDirectories(startPath) Dim subStorage As JolietDiscMasterStorage = _ storage.CreateSubFolder(Path.GetFileName(dir)) AddFilesToStorage(subStorage, dir, recurse) Next End If Dim file As String For Each file In Directory.GetFiles(startPath) storage.AddFile(file, Path.GetFileName(file)) Next End Sub
With that done, creating the disc is easy: firstly any existing content in the image is cleared, then data is added using the AddData method of JolietDiscMaster and finally the disc is recorded using the DiscMasterRecordDisc method:
''' <summary> ''' Creates a data CD from the specified files ''' </summary> ''' <param name="simulate">Simulate CD burning</param> ''' <param name="ejectWhenComplete"><c>true</c> to eject the CD ''' tray when the burn is complete, <c>false</c> otherwise</param> ''' <param name="overwrite"><c>true</c> to overwrite existing files ''' on CDRW media, <c>false</c> otherwise</param> Public Sub CreateCD( _ ByVal simulate As Boolean, _ ByVal ejectWhenComplete As Boolean, _ ByVal overwrite As Boolean ) '// Ensure we don't have anything in the stage discMaster.ClearFormatContent() '// Stage the content jolietDiscMaster.AddData(overwrite) '// burn the disc discMaster.RecordDisc(simulate, ejectWhenComplete) '// Easy! End Sub
Whilst burning is in progress, there are six events to respond to:
That is really all you need to do to create the disc; however, if you want to be able to respond to cancellations, or to show progress you will need to write your application so the burn runs on a background thread. The construction of the wrapper makes this very easy to do using BeginInvoke.
Buring a CD is typically a long operation. If you invoke a burn operation on the user-interface thread, then the application will appear to be locked up whilst the burn occurs. Under XP and above, a feature was added which allows the caption and border of the window to be unfrozen if XP detects that the application has been locked up for a significant length of time. After this point in .NET Framework applications, calls to update controls and so forth no longer have any effect.
Therefore we want a way to invoke the CD burn on a background thread. Since the IMAPI wrapper makes a call to check whether the burn is cancelled at frequent intervals, and this is done through an event, there is also a safe way to cancel a burn operation at any time.
Any method in a class can be invoked asynchronously in .NET by creating a delegate for it. Once you have done this, the compiler is responsible for automatically creating three methods for the delegate:
This makes asynchronous invocation easy. There are four coding steps:
Here's the code for doing this in VB and C#. Unsurprisingly the code is very similar; the only real difference being VB's odd use of AddressOf to refer to delegates. In this case the method I want to call is the CreateCD method implemented in my DataCDCreator class. This method takes three boolean parameters (for simulate burn, eject when complete and overwrite) and has no return value:
VB Code for Asynchronous Invocation
''' <summary>''' Delegate representing the CreateCD method''' </summary>Public Delegate Sub CreateCDDelegate( _ ByVal simulate As Boolean, _ ByVal ejectWhenComplete As Boolean, _ ByVal overwrite As Boolean)
Private creator As DataCDCreator = Nothing Private createCDHandler As CreateCDDelegate = Nothing ' Asynchronously invoke the creator creator = New DataCDCreator(discMaster, jolietDiscMaster) creator.AddDirectory(txtFolder.Text, True) createCDHandler = AddressOf creator.CreateCD Dim callback As AsyncCallback = AddressOf createCD_Complete Dim ar As IAsyncResult = createCDHandler.BeginInvoke( _ simulate, ejectWhenComplete, overwrite, callback, Nothing) ''' <summary> ''' Called when CD creation completes ''' </summary> ''' <param name="ar">Result of method call (none)</param> Private Sub createCD_Complete(ByVal ar As IAsyncResult) ' NB should surround with try - catch - end try SetApplicationMode(False) createCDHandler.EndInvoke(ar) End Sub
C# Code for Asynchronous Invocation
/// <summary> /// Delegate representing the CreateCD method /// </summary> public delegate void CreateCDDelegate( bool simulate, bool ejectWhenComplete, bool overwrite);
private DataCDCreator creator = null; private CreateCDDelegate createCDHandler = null; // Asynchronously invoke the creator creator = new DataCDCreator(discMaster, jolietDiscMaster); creator.AddDirectory(txtFolder.Text, true); createCDHandler = new CreateCDDelegate(creator.CreateCD); AsyncCallback callback = new AsyncCallback(createCD_Complete); IAsyncResult ar = createCDHandler.BeginInvoke( simulate, ejectWhenComplete, overwrite, callback, null); /// <summary> /// Called when CD creation completes /// </summary> /// <param name="ar">Result of method call (none)</param> private void createCD_Complete(IAsyncResult ar) { // NB should surround with try-catch SetApplicationMode(false); createCDHandler.EndInvoke(ar); }The sample application here is rather trivial, in that all it allows you to do is to copy an existing directory to the CD. However, that's not an actual limitation, since when you create the storage you can specify that any file is mapped to a different path and or file on the destination CD. A more complete application would allow you to drag files from any location to the CD, and rename them if possible.
You could use this code to create an almost unattended CD writer (the only thing you need to do is to ensure suitable media is available in the drive) rather than having a UI.
This article demonstrates how to create Data CDs from VB or C# using the IMAPI Wrapper. Although the sample has a simple UI it performs all of the major operations you'll need to perform and should be easy to extend.
| php 그래프 그리기 (0) | 2009.04.22 |
|---|---|
| C# USB viewer open source (0) | 2009.04.22 |
| 파이썬으로 하는 웹 클라이언트 프로그래밍 (0) | 2009.04.22 |
| TCP/IP 소켓 프로그래밍 with C# (0) | 2009.04.22 |
| Delphi for php 사용안내 (0) | 2009.04.22 |
| 파이썬으로 하는 웹 클라이언트 프로그래밍 | |
| 저자: 데이브 워너(Dave Warner), 역 전순재 웹 클라이언트 프로그래밍은 웹에서 정보를 찾게 도와주는 강력한 테크닉이다. 웹 클라이언트는 (웹 주소 앞에 붙은 http) 하이퍼 텍스트 전송 프로토콜[1]을 사용하여 웹 서버로부터 데이터를 열람하는 프로그램 모두를 말한다. 웹 브라우저는 클라이언트이다. 웹 크롤러(crawler) 역시 클라이언트이다. 이 프로그램은 웹을 자동적으로 돌아다니면서 정보를 수집한다. 웹 클라이언트를 사용하면 웹에서 다른 사람들이 제공하는 서비스들을 이용할 수 있으며 웹 사이트에 역동적인 특징들을 추가할 수도 있다. 개발자들이 사용하는 툴박스에는 자연스럽게 웹 클라이언트 프로그래밍이 들어있다. 펄(Perl) 열성팬들은 이미 수년간 웹 클라이언트 프로그래밍을 이용해 왔다. 이런 웹 클라이언트 프로그래밍은 파이썬으로 처리하면 편리성과 유연성이 더욱 높은 수준에 이른다. 여기에 필요한 모든 기능들은 모듈 3개로 해결할 수 있다. HTTPLIB, URLLIB, 그리고 더 새로워진 XMLRPCLIB가 바로 그것들이다. 진정한 파이썬 스타일로, 각 모듈은 기존의 모듈 위에 구축되어 애플리케이션에 견고하면서도 잘 디자인된 기반을 제공한다. XMLRPCLIB는 다음에 논하기로 하고 본 기사에서는 첫 번째 모듈 두 개에 대해 다루겠다. 우리가 볼 예제에서는 미어캣(Meerkat)을 사용하겠다. 이럴 경우 여러분이 필자와 같은 생각을 가지고 있다면 시간을 들여 오픈 소스 공동체의 동향과 개발 상황들을 추적해서 경쟁력을 확보할 것이다. 미어캣(Meerkat) 은 이 작업을 훨씬 더 쉽게 만들어주는 도구이다. 미어켓은 오픈 와이어 서비스(open wire service)로서 오픈 소스 컴퓨팅과 관련된 방대한 양의 정보를 수집하고 정리한다. 미어캣의 브라우저 인터페이스는 유연하고 맞춤가능하지만, 웹 클라이언트 프로그래밍을 사용하면 우리는 이 정보를 훓어보고, 추출하는 것은 물론이고 나중에 사용하기 위해 오프 라인에 저장할 수도 있다. 우리는 먼저 HTTPLIB를 상호대화적으로 사용하여 미어켓에 접근할 것이다. 그리고 나서 URLLIB를 통해 미어켓의 개방 API(Meerkat's Open API)에 접근해 들어가 맞춤가능한 정보 수집도구를 만들어 볼 것이다. HTTPLIB HTTPLIB 는 소켓(socket) 모듈을 살짝 감싼 포장자(wrapper)이다. 앞에서 언급한 3개의 라이브러리 중에서 웹 사이트에 접근할 때 가장 제어가 쉬운 모듈이 HTTPLIB이다. 그렇지만 과업을 달성하기 위해서는 추가 작업을 더 해야만 제대로 제어할 수 있다. http 통신규약(protocol)은 "정보를 저장하지 않기(stateless)" 때문이다. 따라서 이전의 요구는 전혀 기억하지 않는다. 각 요구에 대해 여러분은 HTTPLIB 객체를 새롭게 구성하여 웹 사이트에 접속해야 한다. 요구들은 웹 서버와 대화를 형성하고 웹 브라우저를 흉내낸다. 라엘 돈페스트(Rael Dornfest)의 개방 API를 사용해서 미어켓에 접속해 보자. 그리고 어떤 결과를 얻는지 살펴 보자. 대화는 일련의 서술문들을 구축함으로써 시작된다. 먼저 원하는 작업이 무엇인지 서술한다. 그리고 나서 웹 서버에게 여러분을 식별시킨다. >>> import httplib>>> host = 'www.oreillynet.com'>>> h = httplib.HTTP(host)>>> h.putrequest('GET', '/meerkat/?_fl=minimal')>>> h.putheader('Host', host)>>> h.putheader('User-agent', 'python-httplib')>>> h.endheaders()>>>GET 요청은 어느 페이지를 받기 원하는지 서버에게 전달한다. 호스트 헤더(Host header)는 질의하고자 하는 도메인 이름을 서버에게 전달한다. 현대적인 서버들은 HTTP 1.1을 사용하여 여러 도메인을 같은 주소에서 사용할 수 있다. 만약 서버에게 어떤 도메인 이름을 원하는지 알려주지 않는다면, 여러분은 '302' 출력전환(redirection) 응답을 반환 코드로 얻게 될 것이다. 사용자-에이전트 헤더(User-agent header)는 서버에게 여러분이 어떤 종류의 클라이언트인지 알려 준다. 그래야만 서버는 여러분에게 보낼 수 있는 것과 없는 것이 무엇인지를 이해할 수 있기 때문이다. 이것이 웹 서버가 요구를 처리하기 위해 필요한 정보이다. 다음으로 여러분은 응답을 요구한다. >>> returncode, returnmsg, headers = h.getreply()>>> if returncode == 200: #OK... f = h.getfile()... print f.read()...이렇게 하면 현재의 미어켓 페이지를 간략한 형태(minimal flavor)로 출력할 것이다. 응답 머리부와 응답 내용은 개별적으로 반환되며, 이렇게 하면 반환된 데이터의 문제를 해결하거나 해석하는데 모두 도움이 된다. 만약 응답 머리부를 보고 싶다면, print headers를 사용하면 된다. HTTPLIB 모듈은 소켓 프로그래밍의 기계적인 면을 구별해준다. 게다가 HTTPLIB 모듈은 버퍼링을 위해 파일 객체를 사용하기 때문에 친숙하게 데이터 조작에 접근할 수 있지만 더욱 강력한 웹 클라이언트 애플리케이션을 위한 빌딩 블록이나 문제가 생긴 웹사이트와 상호 대화를 나누기 위한 빌딩 블록으로 더 잘 맞는다. HTTPLIB 모듈이 가지는 유용한 디버그 능력은 두 영역 모두에 도움을 준다. 객체 초기화 후에 어느 곳에서나 h.set_debuglevel(1) 메소드를 호출하면 HTTPLIB에 접근할 수 있다. (예제에서는 다음의 h = httplib.HTTP(host) 라인이다). 디버그 수준이 1에 설정되어 있으면 HTTPLIB 모듈은 getreply()을 호출한 결과들과 요청들을 화면에 응답할 것이다. 파 이썬의 상호대화적인 특성 덕분에 즐겁게 HTTPLIB를 사용하여 웹 사이트를 분석할 수 있다. 이 모듈을 익히면 웹 사이트의 문제점들을 진단하기 위한 강력하고 유연한 도구를 가지게 되는 것이다. 또 시간을 가지고 HTTPLIB에 대한 소스를 살펴보라. 200줄도 안되는 코드임에도 불구하고, HTTPLIB를 사용하면 빠르고 쉽게 파이썬으로 소켓 프로그래밍을 시작할 수 있다. URLLIB URLLIB 는 HTTPLIB에서 발견되는 기능에 대해 세련된 인터페이스를 제공한다. URLLIB 모듈은 웹 사이트를 분석하는 것보다는 데이터 그 자체를 찾아 내는데 가장 유용하게 사용된다. 다음 코드는 URLLIB를 사용해서 위와 똑같은 상호작용을 한다. (주의: 마지막 줄을 화면 출력을 위해 두 줄로 쪼개었지만, 여러분의 스크립트에서는 나누지 말 것!) >>> import urllib>>> u = urllib.urlopen('http://www.oreillynet.com/meerkat/?_fl=minimal')이것이 다이다! 한 줄로 미어켓(Meerkat)에 접근해서 데이터를 얻었으며, 그 데이터를 임시 저장소에 보관했다. 해더 정보에 접근하려면 >>> print u.headers그리고 전체 파일을 보려면 >>>print u.read()그러나 이것이 전부는 아니다. URLLIB는 HTTP뿐만 아니라 FTP, Gopher, 심지어는 같은 방식으로 지역 파일에도 접근할 수 있다. 이 모듈이 제공하는 많은 유틸리티 기능에는 url 해석하기, 문자열을 url-안전 형태로 코드전환(encode)하기, 그리고 한참 긴 데이터 전송 중에 진행 표시를 제공하기가 있다. 미어켓을 사용하는 예제 하나 한 그룹의 고객(client)들이 있는데 그들이 최신 리눅스 소식을 이메일로 꾸준히 받아보기를 바라고 있다고 상상해보자. 우리는 짧은 스크립트를 작성할 수 있다. URLLIB를 사용하여 이 정보를 Meerkat으로부터 얻는다. 링크의 목록을 구축한다. 그리고 그 링크들을 나중에 전송하기 위해 파일에 저장한다. 미어켓(Meerkat)의 저자인 라엘 돈페스트(Rael Dornfest)는 미어켓 API를 통해 우리 대신 대부분의 작업을 이미 완성해 놓았다. 남아있는 것은 요구를 구성하고, 링크를 해석하며, 나중에 전송하기 위해 그 결과를 저장하는 것 뿐이다. 단 지 이것 때문에 사람들이 미어캣으로 전향하는 것일까? 이러한 "정보받기(passive)" 서비스를 제공하면 사람들은 그 정보를 한가할 때 볼 수 있다. 그리고 그 정보를 골라서 친숙한 형식(예를 들어 이메일)으로 저장할 수 있다. 월요일 아침에 메일함에서 뉴스들이 도착하기를 기다리기만 하면, 한 주간 "말려 올라간" 정보들을 하나도 놓치지 않을 것이다. 미어캣의 간략한 형식(minimal flavor)은 기사가 15개로 제한되므로 데이터를 놓칠 가능성을 줄이기 위해 우리는 스크립트를 (즉, Unix의 cron 작업 또는 NT의 AT 명령어를 사용하여) 매 시간 실행시킬 것이다. 여기에 우리가 사용할 url이 있다 (주의: 우리는 이 줄을 두 개의 줄로 나누어 화면에 표시했다. 이 URL을 사용한 결과는 여기에서 볼 수 있다). http://www.oreillynet.com/meerkat/?p=5&t=1HOUR&_fl=minimal&_de=0&_ca=0&_ch=0&_da=0이 코드는 지난 한 시간 동안에 있었던 모든 리눅스 이야기들(profile=5)을 끌어 와서, 데이터를 간략한 형식(minimal flavor)으로 보여준다. 설명도 없고, 범주정보도 없으며, 채널 정보, 데이터 정보도 없다. 우리는 또한 정규 표현식 모듈의 도움을 받아 링크 정보를 추출하고 출력결과를 추가 모드로 열려진 파일 객체로 방향전환할 것이다. 결론 우 리는 겨우 이 모듈들의 표면만을 건드려 보았다. 웹 클라이언트 작업에 사용할 수 있는 것 말고도 파이썬에는 다른 많은 네트워크 프로그래밍 모듈을 사용할 수 있다. 웹 클라이언트 프로그래밍은 특히 방대한 양의 계산표형 테이터를 다룰 때 유용하게 사용할 수 있다. 최근의 한 전자 데이터 교환(EDI) 프로젝트에서 우리는 웹 클라이언트 프로그래밍을 사용하여 거추장스러운 독점 소프트웨어 패키지를 우회하였다. 갱신된 가격 정보를 웹으로부터 직접 얻어서 데이터베이스에 집어 넣었다. 그렇게 함으로써 우리는 많은 시간을 절약하고 좌절감을 극복할 수 있었다. 웹 클라이언트 프로그래밍은 웹 사이트의 구조와 견고성을 테스트하는 데에도 유용하게 사용될 수 있다. 일반적으로는 죽은 링크들을 점검하는 방법으로 사용된다. 표준 파이썬 배포본에는 이것에 대한 완전한 예제가 딸려온다. 이 예제는 URLLIB에 기초한다. Tk-기반의 프론트 엔드[2] 모듈인 웹체커(Webchecker)는 파이썬 배포본의 tools 하부디렉토리 아래에서 찾아볼 수 있다. 또다른 파이썬 도구인 린봇(Linbot) 은 URLLIB 모듈의 기능을 개선해 준다. 린봇으로 여러분은 웹 사이트의 문제를 모두 해결할 수 있다. 웹 사이트들이 점점 더 복잡해짐에 따라 웹 사이트의 질을 확인하기 위해서는 다른 웹 클라이언트 애플리케이션들이 필요하게 될 것이다. 웹 클라이언트 프로그래밍에는 함정이 하나 있다. 여러분의 프로그램은 페이지의 형식이 조금만 변경되어도 영향을 받는다. 반드시 웹 사이트가 오늘 데이터를 출력하는 방식이 내일도 그대로 유지된다고 장담할 수는 없다. 페이지의 형식이 바뀌면 프로그램도 바뀌어야 한다. 사람들이 XML에 그렇게 흥분하는 이유 중 하나가 바로 이것 때문이다. 웹에서 데이터에 태그를 붙여 의미를 주면 형식은 중요하지 않게 된다. XML 표준이 진화하고 범세계적으로 인정됨에 따라, 훨씬 더 쉽게 그리고 튼튼하게 XML 데이터를 처리하게 될 것이다. 우리가 여기에서 다룬 도구들에는 약간의 제한이 있다. HTTPLIB 모듈과 URLLIB모듈은 클라이언트-기반 작업에는 탁월하지만 오직 한 번에 한 개의 요청만을 처리할 수 있기 때문에 서버를 구축하는데 사용해서는 안된다. 비동기적인 처리방법을 제공하기 위해 샘 러싱(Sam Rushing)은 멋진 도구모음을 구축하였다. 이 도구모음은 asyncore.py 를 포함하여 표준 파이썬 배포본에 딸려 온다. 이 접근법을 사용하는 가장 강력한 예제는 조프(ZOPE)이다. 조프는 애플리케이션 서버로서 샘 러싱(Sam Rushing)의 메듀사 엔진(Medusa engine)을 사용하여 구축한 빠른 http 서버를 포함하고 있다. 다음 기사에서는 XML과 웹 클라이언트 프로그래밍을 어떻게 XMLRPCLIB 모듈에 결합하는지에 대해 논의해볼 생각이다. XML을 사용하면 미어켓(Meerkat) API로부터 더욱 많은 기능을 짜낼 수 있다. 각주 [1] Hyper Text Transfer Protocol [2] front end: 프론트 엔드 예) GUI는 front end 이며 구현된 기능들은 back end이다. 데이브 워너(Dave Warner)는 Federal Data Corporation사의 선임 프로그래머이자 데이터베이스 관리자(DBA)이다. 그는 P자로 시작하는 언어(Python, Perl, PowerBuilder)로 관계형 데이터베이스에 접근하는 방법을 연구하고 있다. | |
| C# USB viewer open source (0) | 2009.04.22 |
|---|---|
| Writing Data CDs (0) | 2009.04.22 |
| TCP/IP 소켓 프로그래밍 with C# (0) | 2009.04.22 |
| Delphi for php 사용안내 (0) | 2009.04.22 |
| flash plot (0) | 2009.04.21 |
| Writing Data CDs (0) | 2009.04.22 |
|---|---|
| 파이썬으로 하는 웹 클라이언트 프로그래밍 (0) | 2009.04.22 |
| Delphi for php 사용안내 (0) | 2009.04.22 |
| flash plot (0) | 2009.04.21 |
| contextmenustrip 메뉴에 하위메뉴 동적으로 생성 (0) | 2009.04.15 |
Video 1 - http://www.phpres.com/help/manual/delph ··· orld.htm
Video 2 -
http://www.phpres.com/help/manual/delph ··· demo.htm
Video 3 -
http://www.phpres.com/help/manual/delph ··· ates.htm
Video 4 -
http://www.phpres.com/help/manual/delph ··· tion.htm
Video 5 -
http://www.phpres.com/help/manual/delph ··· maps.htm
Video 6 -
http://www.phpres.com/help/manual/delph ··· hort.htm
Video 7 -
http://www.phpres.com/help/manual/delph ··· gger.htm
Video 8 -
http://www.phpres.com/help/manual/delph ··· grid.htm
Video 9 -
http://www.phpres.com/help/manual/delph ··· ding.htm
(출처 :http://bbs.phpres.com/thread-999-1-1.html)
| 파이썬으로 하는 웹 클라이언트 프로그래밍 (0) | 2009.04.22 |
|---|---|
| TCP/IP 소켓 프로그래밍 with C# (0) | 2009.04.22 |
| flash plot (0) | 2009.04.21 |
| contextmenustrip 메뉴에 하위메뉴 동적으로 생성 (0) | 2009.04.15 |
| Pixel Color Under Mouse (0) | 2009.04.09 |
The source file include class files, so this is a Flash MX 2004 movie. Otherwise, it can be done by Flash MX.
Evaluate the equation object
I have discussed in previous session how to parse a string and get the value of an equation. At the end, I also discussed how to handle an equation string with variables. So, it is not difficult to get the value of "sin(x)" when we set x=0.3;
When we draw equation graph, we need to sample many x values and get the result of the equation before we plot those data out. We can accomplish this by repeated setting x and parsing the equation to get a new result.
However, to parse an equation string, we need to screen each character for existance of parenthesis and existance of any operator in the operatorSet array. It is time consuming.
Since what gets changed is the variable value only, the existence and position of the operators and parenthesis are the same as before , repeated parsing is not necessary. We can store down the operators and parenthesis. That is what my EquationObject class serves.
By this algorithm, to handle 100 sample x and get 100 y value is not a hard job any more. My evaluator does not evaluate the equation string. It evaluate the instance of EquationObject.
In this movie, about 400 x values are sampled. This is faster and more efficient.
The fit of Y range
Here is the scenario. We set x and y range from 0 to 8. We plot the equation "sin(x)". Well, half of the y points fall into the negative region. That means half of the curve is out of the lower bound of the canvas. Besides, the curve is located low and occupies only one-eighth of the canvas leaving a large blank area in the upper half. This is ugly and stupid.
To correct this, we need to calculate the Y range of the curve. We walk through each y value in the y Array and pick the maximal value and minimal value. Calculate the y range by yMax-yMin so that we can plot and fit our curve to the canvas.The highest point of the curve should fall on the top edge of the canvas and the lowest point of the curve should fall on the bottom edge of the canvas.
Unfortunately, the policy is not always possible. There are bugs. Lets try to remove the bug.
P.S. in my source file, if we set yMin, yMax then the automatic fit function is disabled. This is necessary in some condition, such as doing a comparison between two equations.
The infinity - range too big
Check this scenario. How to plot the equation "1/x" with x ranging from -1 to 1 ?
When x=0, the value is infinity. Even worse, when x is near the x, the value 1/x is very very large. If we accept that y value, then the y range is very large. The curve is very ugly.
Can you guess what it had looked like ? Well, the graph shows a max point at the upper edge and all other points fall at the lower edge of the canvas. Yes, since the y range is very large, all values are zoomed out as if those values are nearly 0 except the max point.
To correct this, I have to skip off those infinity values or values that are un-acceptably large compared with other values. The algorithm should not be too complex. Flash can easily hang out for complex algorithm.
I write a simple script. I calculate the slope of the curve. When the curve is curving upward or downward too sharply, I take that point as infinity and skip it off. Mathematically, this algorithm may not be so reasonable, but it does serve our goal.
So, if we plot the equation "1/x" from -1 to 1, we see the points near the x=0 zone are missing.
The flat line - range too small
Scenario: How to plot the equation "sin(x)^2+cos(x)^2" with whatever x range ?
Well, for any x value, the result theoretically is always 1. So we expect to see a flat line on our canvas. No ?
My script would try to put the maximum value at the upper edge and minimum value at the lower edge of the canvas. If the "curve" is a flat horizontal line, how could it possibly do this ?
Can you guess how this equation had been plot ? Well, the result is a bizzare up and down spike.
Flash has limitation in calculation of float point. Besides, the sin and cos functions are just giving estimated values. In fact, when Flash calculate sin(x)^2+cos(x)^2, it gives a value "almost" 1 but not just 1. So, the result of the plot is still a curve with minute up and down not just a flat line. Since the difference between y max and y min is minute, the range is minute and the zoom-in effect is large. The end result is magnification of the up and down of the curve.
To correct this, we add some script to rule out such condition. When y range is too small, we add 5 as its maximum value and subtract 5 as its minimum value.
make the grid scales
Scenario: If I my bottom value is 10.1 and top value is 90, I want to draw grid lines at position where it represent 20- 40- 60- 80 - that counts 4 grid lines. If the top value is 55, I would draw grid lines at 20-30-40-50- total 4 lines. If the top value is 30, then I draw lines at 15 - 20 - 25 -30 total 4 lines.
Principle 1 : I want to keep the number of grid lines around 4 lines, 3 or 5 are acceptable.
Principle 2 : I want the grid line position "rounded" to 0 or 5 if possible. Positions such as 53- 76 -99 -122 should be avoid. In stead, I would hope it to be 50 - 75 -100 -125, although it may be one line more or less.
Well, it is more difficult than I had expected. So, I can not but use a brutal way.
First, I estimate what is the power of 10 for the space. Is it 0.01, or 0.1, or 1 or 10, or 100, or 1000 ? This is done through the log10. The script is like this : Math.floor(Math.log(dx)/Math.LN10);
For a result such as 10, then I test 2, 5, 10, 20, 50 and see how many lines I need to draw, if it counts less than 5, accept it.
If anyone knows a better way, please email me. I would appreciate sincerely.
Sampling limitation
Here is scenario: Plot a graph on to a canvas of 300-pixel-wide for equation "y=sin(x)", with x=-300 to 300.
The result is very ugly and useless because we plot it with in-adequate x sampling. Not every "peak" of the sin wave gets caught. So, not only the straight lines replace the curves, the repeated peaks in the graph do not sit at the same height as we expected.
Lets go back to that scenario. How about plot is with x range 0 to 8. The result is a beautiful curve. Is this beautiful sin wave plot accurate enough ? Here we see two peaks. Are they at the same height ? No. Not exactly.
The peak should occurr when x=(Math.PI)/2 , around half of 3.14159..... I dont think we pick that point exactly.
Theoretically, the peak when x=PI/2 should be at height of 1. No, in our graph, no single Y value is exactly 1.
How many sampling is "enough" ? I dont think there is an easy answer.
The equation grapher
| TCP/IP 소켓 프로그래밍 with C# (0) | 2009.04.22 |
|---|---|
| Delphi for php 사용안내 (0) | 2009.04.22 |
| contextmenustrip 메뉴에 하위메뉴 동적으로 생성 (0) | 2009.04.15 |
| Pixel Color Under Mouse (0) | 2009.04.09 |
| [C#]마우스 좌표 얻기 (0) | 2009.04.08 |
| Delphi for php 사용안내 (0) | 2009.04.22 |
|---|---|
| flash plot (0) | 2009.04.21 |
| Pixel Color Under Mouse (0) | 2009.04.09 |
| [C#]마우스 좌표 얻기 (0) | 2009.04.08 |
| EVC 4.0 프로그래밍의 준비 (0) | 2009.04.06 |
This is a feature that I wanted for a tool I’m doing. I have a color selection control that can select the color of the pixel under the mouse position from the entire application window. I searched the web for a solution and I found a cool implementation from theWPFblog, as Lee Brimelow explains:
“I tried many different ways of doing this but the cleanest was to use the CroppedBitmap class. As you can see in the code below, I first pull out a 1×1 pixel cropped bitmap from the color picker image that is directly below the mouse. Then it’s just a matter of copying the 1 pixel into a byte array and reading the RGB values. There are 4 bytes in every pixel which corresponds to the RGB colors and 1 byte for alpha. To change the color of the rectangle I simply create a new SolidColorBrush from the RGB values. I can think of many great uses for this! Click on the image at the left to check out the app. The C# source code is listed below so you can check out exactly how I implemented it.“
The code can be found here.
Lee’s solution is not good enough for me because I need a color from a pixel found in the entire client area of my application, and Lee’s solution forces me to have a BitmapSource to take the pixel from it.
I found a cleanest way to do that, maybe not clean in “WPF” speaking but using only three simple Win32 functions:
private struct POINT{ public uint X; public uint Y;}[DllImport("gdi32")]private static extern int GetPixel(int hdc, int nXPos,int nYPos);[DllImport("user32")]private static extern int GetWindowDC(int hwnd);[DllImport("user32")]private static extern int GetCursorPos(out POINTAPI lpPoint);[DllImport("user32")]private static extern int ReleaseDC(int hWnd, int hDC);
And here is the GetPixelColor method implementation:
private static SolidColorBrush GetPixelColor(Point point){ int lDC = GetWindowDC( 0 ); int intColor = GetPixel( lDC, (int)point.X, (int)point.Y ); // // Release the DC after getting the Color. ReleaseDC( 0, lDC ); //byte a = (byte)( ( intColor >> 0x18 ) & 0xffL ); byte b = (byte)( ( intColor >> 0x10 ) & 0xffL ); byte g = (byte)( ( intColor >> 8 ) & 0xffL ); byte r = (byte)( intColor & 0xffL ); Color color = Color.FromRgb( r, g, b ); return new SolidColorBrush( color );}
With GetWindowDC( 0 ) I ask for the entire window DC, which then I use with GetPixelColor that retrieves the color value from position.
The System.Windows.Media.Color class in WPF doesn’t have a FromArgb method that accepts a integer value of the color as its counterpart from System.Drawing.Color, so I break apart the RGB components from integer value.
Using it:
protected override void OnMouseMove(MouseEventArgs e) { POINT point; GetCursorPos( out point ); Point pos = new Point( point.X, point.Y ); this.StrokeBrush = GetPixelColor( pos ); }This is an alternative solution, for getting the color under the mouse position even when you don’t have a BitmapSource to take it from or you are mixing WinForms or Win32 with WPF.
Have fun!
| flash plot (0) | 2009.04.21 |
|---|---|
| contextmenustrip 메뉴에 하위메뉴 동적으로 생성 (0) | 2009.04.15 |
| [C#]마우스 좌표 얻기 (0) | 2009.04.08 |
| EVC 4.0 프로그래밍의 준비 (0) | 2009.04.06 |
| 액션 스크립트 용어 및 정리 (0) | 2009.03.17 |
| contextmenustrip 메뉴에 하위메뉴 동적으로 생성 (0) | 2009.04.15 |
|---|---|
| Pixel Color Under Mouse (0) | 2009.04.09 |
| EVC 4.0 프로그래밍의 준비 (0) | 2009.04.06 |
| 액션 스크립트 용어 및 정리 (0) | 2009.03.17 |
| Introduction to Programming with Managed DirectX 9.0 (0) | 2009.03.09 |
출처: www.propoz.co.kr
안녕하세요. Lucy입니다.
예전에 투데이스피피시에서 간단한 개발 강좌를 부탁하시기에 어떤 것을 가지고 강좌를 할까 고민을 하다가, 그래도 도움이 되는 것을 해보자해서 Windows Mobile 2003과 2003 SE를 위한 공용 텍스트 리더 어플리케이션을 단계별로 만드는 작업을 진행하면서 중요한 부분을 체크해 가는 방식으로 간단히 강좌를 진행하다가, 개인적인 사정으로 중단된 바가 있습니다.
그래서 이곳에서 다시 해당 강좌를 연재하려고 합니다.
먼저 많은 분들이 질문하시는 것들 중에 하나가 PC에서는 Visual Basic, Visual C++, Delphi 등 다양한 개발 도구들이 있는데, Pocket PC에서는 어떤 개발 도구를 쓰느냐 하는 질문입니다.
이 질문에 대한 답변이 첫 회의 주된 내용이 될 듯 하네요.
Pocket PC에서는 다양하다고는 할 수 없지만, 몇몇 개발 도구들이 있습니다. 주로 PC에서 개발해서 Pocket PC에서 실행하는 것이 정석입니다만, 간혹 Pocket C#와 같이 Pocket PC 상에서 직접 작성해서 컴파일하는 도구들도 준비되어 있습니다. 그러나 이런 도구들은 본격적인 개발을 위한 것이라기 보다는 간단한 테스트를 위한 목적으로 많이 사용됩니다.
이 강좌에서는 가장 많이 사용되는 도구인 Microsoft eMbedded Visual C++ 4.0 Service Pack 4 + Microsoft Windows Mobile 2003 SDK + Developer Resources for Windows Mobile 2003 Second Edition을 사용하여 개발을 진행하도록 하겠습니다.
물론 .NET Compact Framework를 이용하여 Managed Code로 작업할 수도 있겠지만, 이 강좌에서는 Native Code로 진행할 예정입니다.
개발을 진행하기 전에 이 강좌를 보시려면 다음의 조건이 어느 정도는 충족되어 있어야 합니다.
1. 개발에 관심이 있어서 관련 서적을 사서 보거나 빌려볼 수 있을 정도의 열정
아래 조건은 필수 조건은 아닙니다만, 없으면 귀찮아지는 것들입니다.
1. 개발에 필요한 수준의 영어 실력 (ㅡ_ㅡ 개발 문서가 전부 영문입니다.)
2. C++에 대한 기본적인 이해 (심층 분석까지 갈 필요는 없습니다.)
3. MFC/API에 대한 기본적인 이해 (심층 분석까지 갈 필요는 없습니다.)
4. Windows 시스템에 대한 기본적인 이해
1. 개발 도구 준비하기
Pocket PC 어플리케이션 개발을 진행하기 위해서 먼저 개발 도구를 준비하셔야 겠지요. Pocket PC는 작지만, 그 위에서 동작하는 어플리케이션을 개발하기 위해서는 많은 준비가 필요합니다.
먼저 PC의 운영 체제는 Windows 2000 Service Pack 2 이상, 혹은 Windows XP Service Pack 1 이상이어야만 합니다. Windows Server 2003에서도 개발을 진행할 수는 있습니다만, 상대적으로 귀찮은 부분이 많이 존재합니다.
그 중에서 권하는 것은 Windows XP Professional Service Pack 2입니다. (Service Pack 2는 굳이 없어도 되겠지만요.)
운영 체제의 요건이 충족된다면 개발 도구를 준비하셔야 합니다.
Pocket PC의 개발 도구는 VS.NET에 연동되어 있는 SDE(Smart Device Extension)를 제외하면 모두 무료로 배포되며, 마이크로소프트의 Pocket PC 개발자 사이트에서 다운로드하실 수 있습니다.
한글 환경에 맞추어 개발하기 위해 필요한 도구들은 다음과 같습니다.
1. Microsoft eMbedded Visual C++ 4.0 (다운로드 페이지) - 영문 버전
CD Key는 다음과 같습니다.
TRT7H-KD36T-FRH8D-6QH8P-VFJHQ
2. Microsft eMbedded Visual C++ 4.0 SP4 (다운로드 페이지) - 영문 버전
3. Microsoft SDK for Windows Mobile 2003-based Pocket PCs (다운로드 페이지) - 영문 버전
4. Developer Resources for Windows Mobile 2003 Second Edition (다운로드 페이지)
5. 한글 Pocket PC 2003 Emulator Image (다운로드)
6. 영문 Pocket PC 2003 SE Emulator Image (다운로드 페이지)
7. 한글 Pocket PC 2003 SE Emulator Image (다운로드)
8. Run-time Type Information Library for the Windows Mobile-based Pocket PC 2003 SDK (다운로드)
위의 항목들을 순서대로 설치하셔야 합니다. 자세한 설치 방법과 설정 방법은 2회에서 다루도록 하겠습니다.
지루한 글 읽어 주셔서 감사합니다.
첫 번째 강좌를 올려드린 이후에 바쁜 일정으로 인해 꽤 오랫동안 강좌를 못한 점 진심으로 사과 드립니다. 이번에는 지난 시간에 이어 설치 부분을 계속 진행하기로 하겠습니다.
개발 도구라는 특성 상 단순히 설치 만으로 설정이 종료되지 않는다는 점 때문에 처음에 설치에 대해 많은 시간을 할애하여 설명하고 있습니다. 하지만 이 강좌의 설정 부분만 잘 숙지하시면 보다 쾌적한 개발 환경을 만끽하실 수 있습니다. 이 강좌의 내용대로 설정을 진행하시면 다음의 환경에 맞는 개발이 가능하게 됩니다.
- 영문 Pocket PC 2003
- 한글 Pocket PC 2003
- 영문 Pocket PC 2003 Second Edition
- 한글 Pocket PC 2003 Second Edition
물론 이를 응용하시면 중국어, 일본어, 독일어 등의 시스템에 맞는 개발도 진행하실 수 있습니다. 전체적으로 귀찮은 설정 작업을 해야한다는 점만 제외하면 어려운 것은 아니므로, 순서대로만 따라하시면 무리없이 설정을 끝내실 수 있습니다.
1. eMbedded Visual C++ 4.0 설치
eMbedded Visual C++ 4.0(이하 eVC4)의 설치는 일반적인 어플리케이션 설치와 같은 방식으로 설치가 진행되며, 마법사 형식(Next 버튼을 눌러서 다음 단계로 진행하는 방식)으로 설치가 진행됩니다.
일반적으로 CD를 가지고 있지 않으신 분들은 Microsoft 사이트에서 다운로드한 압축 자동 해제 파일 형태로 가지고 계실 텐데, 처음 설치 경로는 여러분의 계정 아래의 임시 폴더로 지정되어 있습니다. 반드시 경로를 C:setupevc 등으로 바뀌주시기 바랍니다. 그러지 않으면 설치 파일과 임시 파일들이 한데 섞여 설치가 곤란하게 됩니다. 압축을 다 푸셨으면 C:setupevcsetup.exe 파일을 실행하셔서 설치를 진행하시면 됩니다.
설치 프로그램은 eVC를 설치하기 전에 Platform Builder 4.0을 설치하게 되는데, 아주 특별한 경우를 제외하면 재부팅을 요구하게 됩니다. 이 때 재부팅을 하지 않으면 설치가 더 이상 진행되지 않으므로 반드시 재부팅을 해 주시기 바랍니다. 재부팅 후 설치 프로그램인 setup.exe를 다시 실행하시면 설치가 그 이후부터 계속 진행됩니다.
설치를 진행하다 보면 설치할 항목을 선택하게 되는데, Standard SDK는 설치하실 필요가 없기 때문에 해당 선택 상자를 지워주시면 됩니다.
설치가 끝나면 아까 생성되었던 C:setupevc 폴더는 삭제하셔도 관계 없습니다.
2. eMbedded Visual C++ 4.0 Service Pack 4 설치
eMbedded Visual C++ 4.0 Service Pack 4(이하 SP4)의 설치는 eVC와 비슷하지만 훨씬 간단하게 구성되어 있습니다. 설치 방법은 마찬가지로 압축 해제를 통해 진행하게 되는데, 이 경우에도 가능하면 별도의 폴더를 만들어 설치하도록 하는 것이 좋습니다. 단, SP4는 압축이 풀린 후에 자동으로 설치가 진행되므로 이 점만 유의하시면 됩니다.
3. Microsoft SDK for Windows Mobile 2003-based Pocket PCs 설치
Microsoft SDK for Windows Mobile 2003-based Pocket PCs(이하 PPC2003 SDK)의 설치는 Microsoft Installer(이하 MSI)를 이용하여 설치가 이루어지며, 별도의 설정 변경 없이 설치를 진행하시면 됩니다.
4. Developer Resources for Windows Mobile 2003 Second Edition 설치
Developer Resources for Windows Mobile 2003 Second Edition(이하 DevResSE)의 설치 역시 MSI를 이용한 설치 작업을 진행하시면 됩니다.
설치 후 설정 작업을 해 주어야 하지만, 이 부분은 제일 마지막 단계에서 한꺼번에 설정을 하도록 하겠습니다.
5. 한글 Pocket PC 2003 Emulator Image 외의 에뮬레이터 이미지들 설치
에뮬레이터 이미지들 역시 MSI로 되어 있으므로 일반적인 어플리케이션과 같이 설치를 진행하시면 됩니다.
설치 후 설정 작업을 해 주어야 하지만, 이 부분은 제일 마지막 단계에서 한꺼번에 설정을 하도록 하겠습니다.
6. Run-time Type Information Library for the Windows Mobile-based Pocket PC 2003 SDK 설치
Run-time Type Information Library for the Windows Mobile-based Pocket PC 2003 SDK(이하 RTTI)는 eVC에서 try=catch를 정상적으로 사용할 수 있도록 해 주는 라이브러리입니다.
설치 위치를 C:RTTI로 지정하신 후 압축을 해제하시면 됩니다.
7. 설정하기
지금부터 지루한 설정 작업이 진행됩니다.
7-1. 폴더 지정하기
먼저 eVC를 실행합니다. 시작-프로그램-Microsoft eMbedded Visual C++ 4.0-eMbedded Visual C++ 4.0을 클릭하면 됩니다.
eVC가 실행되면, 먼저 Tools-Options를 선택합니다. Options 대화 상자가 나타나면 Directories 탭을 선택합니다.
Platform은 POCKET PC 2003을 지정하고, CPUs에서 Win32 (WCE emulator)를 지정하고, Show Directories에서 Include files를 선택합니다.
리스트의 제일 아래 빈 박스 부분을 더블 클릭하면 새 폴더를 지정할 수 있는데, ... 버튼을 눌러 폴더 선택 대화 상자를 엽니다. C:PROGRAM FILESDEVELOPER RESOURCES FOR WINDOWS MOBILE 2003 SECOND EDITIONINCPOCKET PC 폴더를 선택하신 후, 해당 라인을 제일 위로 올립니다. 위로 올릴 때는 위쪽 화살표 아이콘을 눌러주면 됩니다.
이제 다시 Show Directories에서 Library files를 선택하고, 마찬가지로 C:PROGRAM FILESDEVELOPER RESOURCES FOR WINDOWS MOBILE 2003 SECOND EDITIONLIBPOCKET PCX86를 추가하고 제일 위로 올립니다.
이제 CPUs를 Win32 (WCE ARMV4)로 변경하신 후 Include files에는 C:PROGRAM FILESDEVELOPER RESOURCES FOR WINDOWS MOBILE 2003 SECOND EDITIONINCPOCKET PC 폴더를 추가하시고, Library files에는 C:PROGRAM FILESDEVELOPER RESOURCES FOR WINDOWS MOBILE 2003 SECOND EDITIONLIBPOCKET PCARM을 추가합니다.
7-2. 에뮬레이터 등록하기
기본적으로 여기까지 진행하시면 영문 Pocket PC 2003 에뮬레이터와 디바이스만 등록이 되어 있는 상태입니다. 한글 Pocket PC 2003과 SE 에뮬레이터를 사용하려면 추가적인 설정이 필요합니다.
eVC가 실행된 상태에서 Tools-Configure Platform Manager를 선택합니다. POCKET PC 2003 아래에 POCKET PC 2003 Device와 Pocket PC 2003 Emulator가 등록된 것을 확인할 수 있습니다. 새로운 디바이스를 등록하기 위해 Add Device 버튼을 클릭합니다. 그러면 New Device 항목이 생성되는데, 이름은 나중에 지정해도 되니 일단 그대로 놔둡니다.
New Device가 선택된 상태에서 Properties 버튼을 클릭하면 디바이스 프로퍼티 대화 상자가 나타나는데, Transport는 TCP/IP Transport for Windows CE를 선택합니다. Startup Server는 Emulator Startup Server를 선택합니다.
Startup Server의 옆에 있는 Configure 버튼을 클릭하면 Emulation Configuration Settings 대화 상자가 나타납니다. Device의 Image에서는 연결할 에뮬레이터 이미지를 지정합니다. 한글판 Pocket PC 2003을 선택하기 위해 KOR POCKET PC 2003을 선택합니다. 이 항목이 없다면 5. 의 에뮬레이터가 정상적으로 설치되지 않은 것이므로 다시 확인을 하셔야 합니다. 나머지 부분은 건드리실 필요가 없으며, OK 버튼을 클릭하면 1차적으로 이미지 지정이 끝납니다.
이미지의 지정이 끝났다면 하단의 Test 버튼을 클릭해 봅니다. 에뮬레이터가 실행되고, 한글판 Pocket PC가 나타난다면 정상적으로 지정이 된 것입니다. OK 버튼을 눌러 설정을 완료합니다. 테스트를 하지 않았다면 테스트를 하지 않았다는 경고 대화 상자가 나타나므로 가급적이면 테스트를 거칠 것을 권합니다.
New Device의 이름을 변경하려면 해당 이름 위에서 클릭을 두 번 해주면 됩니다. 더블 클릭을 하면 설정 대화 상자가 열리므로 더블 클릭을 하면 안 됩니다. 이름은 POCKET PC 2003 Kor Emulator 정도로 바꿔줍니다. Korean Pocket PC 2003 Emulator로 할 수는 있지만, 나중에 에뮬레이터를 선택할 때 정신이 없으므로 가능하면 형태를 기본과 맞춰 주는 것이 좋습니다.
추가적으로 SE의 에뮬레이터도 지정을 해 주면 됩니다. Radio 관련 에뮬레이터는 일반적인 경우 지정할 필요가 없으며, SE는 언어별로 다음의 4가지 이미지만 설정하면 됩니다. (영문/한글을 지정할 경우 4 X 2 = 8개의 이미지를 지정해야 합니다.)
SE Emulator - 240x320 모드
SE Landscape Emulator - 320x240 모드
SE VGA Emulator - 480x640 모드
SE Landscape Emulator - 640x480 모드
7-3. RTTI 설정하기
eVC4를 종료하고, 아까 RTTI를 설치했던 폴더(C:RTTI)로 갑니다. 안에는 Armv4 폴더와 emulator 폴더의 파일들, 그리고 EULA.txt 파일이 있습니다. 해당 파일과 폴더들을 전부 선택한 후 (폴더대로 선택해야 합니다.) C:Program FilesWindows CE Toolswce420POCKET PC 2003Lib 폴더에 복사하거나 옮깁니다.
Lib 폴더 안에도 Armv4 폴더와 emulator 폴더가 있으며, 각각의 파일들이 올바른 폴더 안에 들어가야 합니다.
이로서 개발 도구의 설치가 끝났습니다. 전부 다 마치면 대략 2시간 정도 걸립니다.
감사합니다.
| Pixel Color Under Mouse (0) | 2009.04.09 |
|---|---|
| [C#]마우스 좌표 얻기 (0) | 2009.04.08 |
| 액션 스크립트 용어 및 정리 (0) | 2009.03.17 |
| Introduction to Programming with Managed DirectX 9.0 (0) | 2009.03.09 |
| DirectX Programming in C# (0) | 2009.03.09 |
용어
다른 스크립팅 언어와 마찬가지로 ActionScript는 자체 용어를 사용합니다. 중요한 ActionScript 용어는 다음과 같습니다.
액션은 SWF 파일이 재생되는 동안 SWF 파일에 작업을 지시하는 명령문입니다. 예를 들어 gotoAndStop()은 재생 헤드를 특정 프레임이나 레이블로 보냅니다. 이 설명서에서 액션과 명령문이라는 용어는 같은 의미입니다.
부울은 true 또는 false 값입니다.
클래스는 새 유형의 객체를 정의하기 위해 만들 수 있는 데이터 유형입니다. 클래스를 정의하려면 액션 패널에서 현재 작성하고 있는 스크립트가 아닌 외부 스크립트 파일에 class 키워드를 사용합니다.
상수는 바뀌지 않는 요소입니다. 예를 들어, Key.TAB 상수는 항상 같은 의미로서 키보드의 Tab 키를 나타냅니다. 상수는 값을 비교하는 데 유용합니다.
생성자는 클래스의 속성 및 메서드를 정의하는 데 사용하는 함수입니다. 생성자는 클래스 정의에 포함된 클래스와 동일한 이름을 가진 함수입니다. 예를 들어, 다음 코드에서는 Circle 클래스를 정의하고 생성자 함수를 구현합니다.
// file Circle.as
class Circle {
private var radius:Number
private var circumference:Number
// constructor
function Circle(radius:Number) {
circumference = 2 * Math.PI * radius;
}
}
생성자는 특정 클래스에 기초한 객체를 생성(인스턴스화)할 때에도 사용됩니다. 다음 명령문은 내장 클래스인 Array와 사용자 정의 클래스인 Circle에 대한 생성자입니다:
my_array:Array = new Array();
my_circle:Circle = new Circle();
데이터 유형은 변수나 ActionScript 요소가 보유할 수 있는 정보의 종류를 설명합니다. ActionScript 데이터 유형으로는 String, Number, Boolean, Object, MovieClip, Function, null 및 undefined가 있습니다. 자세한 내용은 데이터 유형을 참조하십시오.
이벤트는 SWF 파일이 재생되는 동안 발생하는 액션입니다. 예를 들어 무비 클립을 로드할 때, 재생 헤드가 프레임에 들어올 때, 사용자가 버튼이나 무비 클립을 클릭할 때, 사용자가 키보드를 누를 때마다 서로 다른 이벤트가 생성됩니다.
이벤트 핸들러는 mouseDown이나 load와 같은 이벤트를 관리하는 특수 액션입니다. ActionScript 이벤트 핸들러의 종류는 이벤트 핸들러 메서드와 이벤트 리스너로 두 가지가 있습니다. 참고로, 이벤트 핸들러의 종류도 on() 및 onClipEvent()로 두 가지가 있으며 이 이벤트 핸들러를 버튼이나 무비 클립에 직접 지정할 수 있습니다. 액션 도구 상자에서 이벤트 핸들러 메서드 또는 이벤트 리스너가 있는 각 ActionScript 객체에는 이벤트 또는 리스너라는 하위 범주가 있습니다. 일부 명령은 이벤트 핸들러 및 이벤트 리스너 모두로 사용될 수 있으며 이 두 하위 범주에 포함될 수도 있습니다.
표현식은 값을 나타내는 ActionScript 심볼의 올바른 조합입니다. 표현식은 연산자와 피연산자로 구성됩니다. 예를 들어 x + 2 표현식에서 x와 2는 피연산자이고 +는 연산자입니다.
함수는 매개 변수를 받고 값을 반환할 수 있는 다시 사용할 수 있는 코드의 블록입니다. 자세한 내용은 함수 만들기를 참조하십시오.
식별자는 변수, 속성, 객체, 함수 또는 메서드를 나타내는 데 사용하는 이름입니다. 첫 문자는 글자, 밑줄(_) 또는 달러 기호($)여야 합니다. 그 이후의 문자는 문자, 숫자, 밑줄 또는 달러 기호여야 합니다. 예를 들어 firstName은 변수의 이름입니다.
인스턴스는 특정 클래스에 속하는 객체입니다. 클래스의 각 인스턴스에는 해당 클래스의 모든 속성과 메서드가 들어 있습니다. 예를 들어, 모든 무비 클립은 MovieClip 클래스의 인스턴스입니다. 따라서 어떠한 무비 클립 인스턴스에서도 MovieClip 클래스의 모든 메서드와 속성을 사용할 수 있습니다.
인스턴스 이름은 스크립트에서 무비 클립 및 버튼 인스턴스를 대상으로 지정할 수 있도록 하는 고유 이름입니다. 속성 관리자를 사용하여 인스턴스 이름을 스테이지의 인스턴스에 지정합니다. 예를 들어, 라이브러리의 마스터 심볼은 counter이고 SWF 파일에 있는 해당 심볼의 두 인스턴스의 이름은 scorePlayer1_mc와 scorePlayer2_mc라고 합니다. 다음 코드는 인스턴스 이름을 사용하여 각 무비 클립 인스턴스에 score라는 변수를 설정합니다.
_root.scorePlayer1_mc.score += 1;
_root.scorePlayer2_mc.score -= 1;
인스턴스 이름을 지정할 때 특수한 접미사를 사용하면 코드를 입력할 때 코드 힌트(코드 힌트 사용 참조)가 표시되도록 할 수 있습니다. 자세한 내용은 접미어를 사용하여 코드 힌트 표시를 참조하십시오.
키워드는 특수한 의미를 가진 예약된 단어입니다. 예를 들어 var는 로컬 변수를 선언할 때 사용하는 키워드입니다. 키워드는 식별자로 사용할 수 없습니다. 예를 들어 var는 올바른 변수 이름이 아닙니다. 키워드 목록을 보려면 키워드를 참조하십시오.
메서드는 클래스와 연관된 함수입니다. 예를 들어 getBytesLoaded()는 MovieClip 클래스와 연관된 내장 메서드입니다. 내장 클래스에 기반한 객체 또는 사용자 정의 클래스에 기반한 객체에 사용하기 위해 메서드 역할을 하는 함수를 만들 수 있습니다. 예를 들어 다음 코드에서 clear()는 이전에 정의한 controller 객체의 메서드가 됩니다.
function reset(){
this.x_pos = 0;
this.x_pos = 0;
}
controller.clear = reset;
controller.clear();
객체는 속성과 메서드의 컬렉션입니다. 각 객체는 특정 클래스의 인스턴스이며 고유 이름이 있습니다. 내장 객체는 ActionScript 언어에 미리 정의되어 있습니다. 예를 들어, 내장 Date 객체는 시스템 시계의 정보를 제공합니다.
연산자는 하나 이상의 값으로부터 새 값을 계산하는 용어입니다. 예를 들어, 더하기(+) 연산자는 두 개 이상의 값을 더하여 새 값을 만듭니다. 연산자가 처리하는 값을 피연산자라고 합니다.
매개 변수는 인수라고도 하며 함수에 값을 전달할 수 있도록 하는 자리 표시자입니다. 예를 들어, 다음 welcome() 함수는 매개 변수로 받은 firstName 및 hobby의 두 값을 사용합니다.
function welcome(firstName, hobby) {
welcomeText = "Hello, " + firstName + "I see you enjoy " + hobby;
}
패키지는 클래스 파일이 하나 이상 포함된 디렉토리이며 지정된 클래스 경로 디렉토리에 있습니다(클래스 경로 이해 참조).
속성은 객체를 정의하는 특성입니다. 예를 들어, _visible은 모든 무비 클립의 속성으로서 무비 클립을 표시할지 또는 숨길지 여부를 정의합니다.
대상 경로는 SWF에 있는 무비 클립 인스턴스 이름, 변수 및 객체의 계층 주소입니다. 무비 클립 속성 관리자에서 무비 클립 인스턴스의 이름을 지정합니다. 기본 타임라인의 이름은 항상 _root입니다. 대상 경로를 사용하여 무비 클립의 액션을 지정할 수 있으며 변수의 값을 가져오거나 설정할 수 있습니다. 예를 들어, 다음 명령문은 stereoControl 무비 클립 안에 있는 volume 변수의 대상 경로입니다.
_root.stereoControl.volume
대상 경로에 대한 자세한 내용은 절대 및 상대 대상 경로 사용을 참조하십시오.
변수는 모든 데이터 유형의 값을 보유하는 식별자입니다. 변수는 만들거나, 변경하거나, 업데이트할 수 있습니다. 변수에 저장된 값을 가져와 스크립트에 사용할 수 있습니다. 다음 예제에서 등호의 왼쪽에 있는 식별자가 변수입니다.
var x = 5;
var name = "Lolo";
var c_color = new Color(mcinstanceName);
변수에 대한 자세한 내용은 변수를 참조하십시오.
| <<플래쉬 액션 스크립트flash action script>> ---------------------------------------------------------------------------- // ..... 주석 기호 /* ..... */주석 기호 ---------------------------------------------------------------------------- r// 리턴 코드(ASC 13) n// 줄바꿈 코드 (ASC 10) rn// 줄바꿈 코드(2줄) t// Tab 코드 (ASC 9) b// Backspce 코드 (ASC 8) & // text 파일 데이타 구분 코드 ---------------------------------------------------------------------------- 산술연산자+, -, *, /, % //%나머지를 구한다 대입연산자=, +=, -=, *=, /=, %= //i+=4 와i=i+4 는 같다 증감연산자++, --//i++와 i=i+1 는 같다 비교연산자==, !=, >, <, >=, <=//!='같지않다' 로 해석 비교연산자=== //숫자 와 문자 구분 a = 5;b = "5";//숫자 5 와 문자 "5" (a == b)//숫자 5 와 문자 "5"는 같다 (true) (a === b) //숫자 5 와 문자 "5" 는 틀리다 (false) 논리연산자&&, ||, ! //그리고(AND), 또는(OR), 아니면(NOT) 조건연산자?( a ) ? b : c ;//a 조건이 맞으면 b 틀리면 c 실행 x=5;y=10;z=(x<6) ? x: y; trace (z); //z 은 5 이다 문자연산자eqnenotoradd//eq(==) ne(!=) not(!) or(||) add(+ 문자열의 연결) ( ) //연산의 순서를 정한다 [ ] //배열을 지정한다 " " //문자를 지정한다 a=1+2;trace(a); //연산 결과 출력.결과는 3 aaa=1;set("ccc", aaa );trace(ccc);//변수에 값을 지정.결과는 1 aaa=1;set("ccc", "aaa");trace(ccc); //변수에 값을 지정.결과는 aaa set("ooo", getProperty ("ppp", _x )); //ppp x 좌표를ooo 에 지정. ---------------------------------------------------------------------------- for (a=1; a<=10; a++){ trace("a="+a); }; //for반복문 for (i=1; i<=120;i+=12) { continue; }; //for step 반복문 while(true) {if(a == 0) { break; }; }; //while반복문 do { if(a == 0) { break; }; };while(true); //do 반복문 if((n == 0) || (n >= 5)&&(n <= 55)!(n=15)) { //if 조건문 gotoAndPlay(1); } else if (n == 2) { gotoAndPlay(2); } else { gotoAndPlay(3); }; num_ch = 3; //switch 조건문 switch (num_ch) { case 1:trace ( " case 1 tested true " );break; case 2:trace ( " case 2 tested true " );break; default:trace ( " no case tested true " ); }; ---------------------------------------------------------------------------- function sumnumber(a,b,c) {return(aaa= a+b+c); };// 함수 sumnumber(1,2,3); trace(aaa); ---------------------------------------------------------------------------- Math.abs(-1)//절대값. 결과는 1 Math.sin(1) //sin 값. 결과는 0.841470984807897 Math.cos(1) //cos 값. 결과는 0.54030230586814 Math.tan(1) //tan 값. 결과는 1.5574077246549 Math.log(2) //log 값. 결과는 0.693147180559945 Math.exp(1) //지수 값.결과는 2.71828182845905 Math.sqrt(9)//제곱근 값.결과는 3 Math.pow(2 , 4) //거듭제곱 값.결과는 16 Math.ceil(1.1)//가까운 정수로 올림 값.결과는 2 Math.ceil(1.5)//가까운 정수로 올림 값.결과는 2 Math.floor(1.2) //가까운 정수로 내림 값.결과는 1 Math.floor(1.7) //가까운 정수로 내림 값.결과는 1 Math.round(1.2) //가까운 정수로 반올림 값.결과는 1 Math.round(1.5) //가까운 정수로 반올림 값.결과는 2 Math.max(1 , 2) //두 정수 중 큰 정수값.결과는 2 Math.min(1 , 2) //두 정수 중 작은 정수값.결과는 1 int(1.12 ); //수치를 정수화. 결과는 1 int(1.82 ); //수치를 정수화. 결과는 1 parseInt("3.2");//문자열을 정수화.결과는 3 parseInt("3.7");//문자열을 정수화.결과는 3 parseInt("5abc"); //문자열을 정수화.결과는 5 parseInt("abc5"); //문자열을 정수화.결과는 NaN parseInt("3E8", 16);//16 진수로 변환. 결과는 1000 parseInt("777", 8); //8 진수로 변환. 결과는 511 parseInt("1010", 2);//2 진수로 변환. 결과는 10 parseFloat("2") // 문자열을 부동점 숫자로 변환.결과는 2 parseFloat("2.4") // 문자열을 부동점 숫자로 변환.결과는 2.4 parseFloat("2.6abc")// 문자열을 부동점 숫자로 변환.결과는 2.6 Number("11")//문자열을 숫자로 변환. 결과는 11 Number("12.34") //문자열을 숫자로 변환. 결과는 12.34 Number("12.34abc")//문자열을 숫자로 변환. 결과는 NaN sss = 123;uuu = sss.toString();// 숫자를 문자로변환.결과는 123 ord("abc");//ASCII 값. 결과는 97 s = "abc"; sss = s.charCodeAt(0);//1번째 ASCII 값 . 결과는 97 s = "abc"; sss = s.charCodeAt(1);//2번째 ASCII 값.결과는 98 chr(65); //ASCII 코드를 문자화.결과는 A String.fromCharCode(64,65,66); //ASCII 코드를 문자화.결과는 @AB Math.random(); // 난수 발생.결과는 0 - 1 사이의 소숫점 포함한 값 random(5); // 난수 발생.결과는 0,1,2,3,4 중 하나 ---------------------------------------------------------------------------- // delete 변수 또는 객체 ; // 변수를 삭제(var 로 선언된 변수는 삭제할 수 없다) account = 1; trace (account) ;// 결과는 1 account = 1; delete account;trace (account);// 결과는 undefined delete onEnterFrame;// 반복 실행 중지 ---------------------------------------------------------------------------- typeof( );// String, Number, MovieClip, Object, Boolean, Function 여부를 지정 trace (typeof(1));// 결과는 Number trace (typeof("1"));// 결과는 String trace (typeof(aaa));// aaa가 무비클립 이라면결과는 MovieClip ---------------------------------------------------------------------------- isFinite( );// 숫자가 유한수이면 true 무한수거나 음의 무한대이면 false trace (isFinite(aaa));// aaa 값이 NaN 이라면 결과는 false ---------------------------------------------------------------------------- Mouse.show(); // 마우스 보임 Mouse.hide(); // 마우스 감춤 myClip.onMouseDown = function () {trace (" depth 무시"); }; // 마우스 누를 때 myClip.onMouseUp = function () {trace ("depth 무시"); };// 마우스 눌렀다 놓을 때 myClip.onMouseMove = function () { trace ("depth 무시"); }; // 마우스 이동할 때 myClip.onPress = function () { trace ("depth 적용"); }; // 마우스 누를 때 myClip.onRelease = function () { trace ("depth 적용 "); };// 마우스 눌렀다 놓을 때 myClip.onReleaseOutside = function () { trace ("Outside"); }; // 마우스 나가서 놓을 때 myClip.onRollOver = function () { trace ("Over called"); }; // 마우스 오버 때 myClip.onRollOut = function () { trace ("Out called"); }; // 마우스 아웃 때 ---------------------------------------------------------------------------- // 단추무비클립 클릭후 액션 스크립트를 넣는다 on (press){ }// 마우스 버튼을 누를 때 };x}o on (release){ }// 마우스 버튼을 눌렀다 뗄 때 on (releaseOutside){}// 마우스 버튼을 누르고 나가서 뗄 때 on (rollOver){}// 마우스 포인트가 위로 올라올 때 on (rollOut){ }// 마우스 포인트가 밖으로 나갈 때 on (dragOver){}// 누른 채로 밖으로 나갔다가 다시 들어올 때 on (dragOut){ }// 마우스버튼을 누르고 바깥으로 드래그할 때 on (keyPress){}// 지정한 키를 누를 때 ---------------------------------------------------------------------------- // 무비클립 클릭후 액션 스크립트를 넣는다 onClipEvent (load) {}// 시작 될때};x}o onClipEvent (unload) {}// 제거 될때 onClipEvent (enterFrame) {}// 트리거 될때 onClipEvent (mouseMove) { }// 마우스가 이동할 때 onClipEvent (mouseDown) { }// 마우스 클릭 시 onClipEvent (mouseUp) { }// 마우스 클릭 후 onClipEvent (keyDown) { }// 키를 누를 때 onClipEvent (keyUp) { }// 키를 눌렀다 놓을 때 onClipEvent (data) {}// loadVariables 또는 loadMovie 액션에서 데이터가 수신될 때 ---------------------------------------------------------------------------- TextField.onChanged = function () { trace ("onChanged called"); }; // 텍스트 필드의 내용이 변경될 때 TextField.onSetFocus = function () { trace ("onSetFocus called"); }; // 텍스트 필드의 내용 부분에 마우스가 클릭 될 때 TextField.onKillFocus = function () { trace ("onKillFocus called"); }; // 텍스트 필드의 내용 바깥 부분에 마우스가 클릭 될 때 TextField.onScroller = function () { trace ("onScroller called"); }; // 텍스트 필드의 내용이 스크롤 될 때 ---------------------------------------------------------------------------- myMovieClip.onData = function () { trace ("onData called"); }; // 무비 클립이 loadVariables 또는 loadMovie 호출로부터 데이터를 받을 때 myMovieClip.onLoad =function () { trace ("onLoad called"); }; // 무비 클립이 load 호출로부터 데이터를 받을 때 myMovieClip.onUnLoad =function () { trace ("onUnLoad called"); }; // 무비 클립이 Unload 때 myMovieClip.stop() // 작업 중지 ---------------------------------------------------------------------------- myDate = new Date(); // 날짜 로드 myDate = new Date (년,월,일,시,분,초); // 날짜 지정 yyyy = (myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + myDate.getDate()); tttt = (myDate.getHours()+ " :" + myDate.getMinutes() + " :" +myDate.getSeconds()); ---------------------------------------------------------------------------- _root.onEnterFrame = function() { }; // 메인화면에서 프레임 반복 onEnterFrame = function() { }; // 심볼화면에서 프레임 반복 ---------------------------------------------------------------------------- tmtm = getTimer(); onEnterFrame = function() { if ( (getTimer()-tmtm) >= 500 ) { tmtm=getTimer(); trace (tmtm); }; // 0.5초후 반복실행 if ( (getTimer()-tmtm) >= 1000 ) { tmtm=getTimer(); trace (tmtm); };// 1초후 반복실행 if ( (getTimer()-tmtm) >= 2000 ) { tmtm=getTimer(); trace (tmtm); };// 2초후 반복실행 }; ---------------------------------------------------------------------------- onEnterFrame = function() { nr += 1;if (nr > 5 ){deleteonEnterFrame;}; // 5번 반복실행후 중지 trace (nr); }; ---------------------------------------------------------------------------- createTextField ("ins", 1, 100, 100, 50, 50) ins.border = true; function callback() { ins._x += 5; if ( ins._x > 400 ) { clearInterval( intervalID );};// 중지 (clearInterval) } var intervalID; intervalID = setInterval( callback, 100 ); //0.1초후 반복실행 (setInterval) ---------------------------------------------------------------------------- #include "script.as" // script.as 파일 넣기 (액션 스크립트 txt 파일) ---------------------------------------------------------------------------- System.useCodepage = true; // 한글 깨짐 방지 trace(System.capabilities.language)// Flash Player가 지원하는 언어. 결과는 ko trace(System.capabilities.hasVideoEncoder) // 지원되는 비디오 인코더. 결과는 true, false. trace(System.capabilities.hasAudioEncoder )// 지원되는 오디오 인코더. 결과는 true, false. trace(System.capabilities.hasAudio)// 오디오 성능이 있는지 여부. 결과는 true, false. trace(System.capabilities.hasMP3)// MP3 디코더가 있는지 여부. 결과는 true, false. ---------------------------------------------------------------------------- escape("abc가나다"); // URL에 사용하기 위해 인코딩. // System.useCodePage= true; 일때 결과는 abc%B0%A1%B3%AA%B4%D9 // System.useCodePage= false; 일때 결과는 abc%EA%B0%80%EB%82%98%EB%8B%A4 ---------------------------------------------------------------------------- trace(targetPath(this)); // 대상 패스를 반환.결과는 _level0.instance1 로 표시 trace(this.valueOf()); // 결과는 _level0 로 표시 ---------------------------------------------------------------------------- trace(this.getBytesLoaded());// 무비클립의 로드된 바이트 수를 알려준다. trace(this.getBytesTotal()); // 무비클립의 전체용량 바이트 수를 알려준다. ---------------------------------------------------------------------------- getURL("C:/")// 탐색기 열기 getURL("C:/Windows/NOTEPAD.EXE"); }; // 메모장 열기 getURL("C:/Program Files/Accessories/WORDPAD.EXE");// 워드패드 열기 getURL("C:/Program Files/Accessories/MSPAINT.EXE");// 그림판 열기 getURL("C:/Windows/CALC.EXE"); // 계산기 열기 getURL ("aaa.exe");// aaa.exe 파일 열기 (message) getURL ("aaa.txt", "_self"); // aaa.txt 파일 열기 getURL ("movie.html", "_self");// movie.html 파일 열기 getURL ("http://www", "_blank"); // http://www 를 새로운 창으로 열기 ---------------------------------------------------------------------------- Stage.showMenu = "true";// 스크린 메뉴 보임 Stage.showMenu = "false"; // 스크린 메뉴 감춤 Stage.scaleMode = "noScale";// 화면의 사이즈를 고정 Stage.align = "TL"; // 화면의 정렬을 T(위) L(왼쪽) //"T" 위 가운데"B" 아래 가운데"L" 가운데 왼쪽"R" 가운데 오른쪽 //"TL" 위쪽 왼쪽 "TR" 위쪽 오른쪽 "BL" 아래쪽 왼쪽 "BR" 아래쪽 오른쪽 Stage.height// 픽셀로 표시된 스테이지의 높이 Stage.width // 픽셀로 표시된 스테이지의 넓이 ---------------------------------------------------------------------------- _root.createEmptyMovieClip("box",1);// 스테이지 테두리 주기 with (_root.box) {moveto(1, 1); linestyle(10, 0x00cc00, 100); lineto(stage.width, 1); lineto(stage.width, stage.height); lineto(1, stage.height);lineto(1, 1); }; ---------------------------------------------------------------------------- fscommand("showmenu", true);// 스크린 메뉴 보임 fscommand("showmenu", false); // 스크린 메뉴 감춤 fscommand("allowscale", true);// 스크린 크기에 따라 무비의 크기도 변함 fscommand("allowscale", false); // 스크린 크기에 따라 무비의 크기도 안변함 fscommand("fullscreen", true);// 풀 스크린 (esc키 누르면 해제) fscommand("fullscreen", false); // 풀 스크린을 원래의 크기로 만든다 fscommand("trapallkeys", true); // 키보드 키 사용할 수 없음 (풀 스크린 일때 esc키 먹통) fscommand("trapallkeys", false);// 키보드 키 사용할 수 있음 fscommand("quit");// 스크린 닫기 fscommand ("exec", "a.exe");// a.exe 파일 실행 (no message) 플래시 무비(exe) 가 위치하는 폴더안에 fscommand 라는 하위 폴더를 만들고 fscommand 디렉토리에a.exe 가 있을때 플래시 무비(exe)를 실행하면 a.exe파일 실행 ---------------------------------------------------------------------------- // getURL 로 javascript 사용하기 var hello = "Hello, World"; getURL("javascript:alert(" "+ hello + "")"); // 메세지 띄우기 getURL("javascript:window.self.close()");// 윈도우창 닫기 getURL("javascript:window.external.AddFavorite('http://','가')" );//즐겨찾기 추가 ---------------------------------------------------------------------------- // fscommand 로 javascript 사용하기 1.fscommand ("messagebox", "This is a Flash."); // aaa.swf flash script 2.파일메뉴 - 제작설정 - 포맷 (HTML체크) - HTML (템플릿: with FSCommand 체크) 3.파일메뉴 - 제작 (파일명은 aaa.swf) -aaa.html 파일이 디렉토리에 만들어 진다 4.aaa.html 파일을 열고function aaa_DoFSCommand(command, args) {아래에 if (command == "messagebox") {alert(args);}; 을 적고 저장 한다 5.aaa.html 실행 (실행후 제작설정 해제) ---------------------------------------------------------------------------- // fscommand 로 javascript 의 변수값 불러오기 1. fscommand ("search", TextFieldvar); // aaa.swf flash script 2. if (command == "search") {// aaa.html script EEEfind = "FFFFFFFF"; window.d0cument.aaa.SetVariable("TextFieldvar", EEEfind) ; return TextFieldvar; }; 3. aaa.html 실행 ---------------------------------------------------------------------------- _root.loadMovie("a.swf");// swf 파일 불러오기 _root.bbb.loadMovie("a.swf") // swf 를 메인에 있는 bbb무비클립인스턴스에 불러오기 _root.loadMovie("a.swf", 1); // swf 를 레벨1로 불러오기 (2 는 1를screen over) _root.loadMovie("aaa.jpg");// jpg 파일 불러오기 _root.bbb.loadMovie("aaa.jpg");// jpg 파일을 메인에 있는 bbb무비클립인스턴스에 불러오기 unloadMovie (1); // 레벨 1에 로드된 무비를 언로드 unloadMovie ("a.swf"); // 현재 무비에 로드된 a.swf 무비를 언로드 _root.bbb.unloadMovie(); // 메인 타임라인의 bbb 무비클립에 로드된 무비를 언로드 this["bbb"].unloadMovie(); // 현재 타임라인의 bbb 무비클립에 로드된 무비를 언로드 sss.bbb.unloadMovie(); // sss 심볼 타임라인의 bbb 무비클립에 로드된 무비를 언로드 ---------------------------------------------------------------------------- button.onPress = function() { _root.loadMovie("aaa.swf"); } // aaa.swf 실행중 초기화 하기 ---------------------------------------------------------------------------- _root["ball_"+counter]._x = 11; //메인 화면의 클립 좌표 this["ball_"+counter]._x = 11;//현재 화면의 클립 좌표 aaa["ball_"+counter]._x = 11; //aaa 심볼 화면의 클립 좌표 ---------------------------------------------------------------------------- this.createEmptyMovieClip("aaa", 1); //무비클립 생성 (2 는 1를 screen over) this.duplicateMovieClip (aaa, bbb, 1); //aaa 무비클립bbb 로 복사 this.bbb.removeMovieClip();//bbb 무비클립 삭제 myClip._visible = true;//클립 보임 myClip._visible = false; //클립 감춤 myClip.swapDepths(100);//클립 깊이 100 으로 지정 (2 는 1를 screen over) myClip.swapDepths(otherClip);//클립 깊이 otherClip 과 바꿈 for (i=1; i<=360; i++){//클립 복사 duplicateMovieClip (ins1, "mc"+i, i); setProperty ("mc"+i, _x, random(300)); setProperty ("mc"+i, _y, random(300)); setProperty ("mc"+i, _alpha, random(300)); setProperty ("mc"+i, _xscale, 150); setProperty ("mc"+i, _yscale, 150); }; for (i=1; i<=360; i++){//클립 복사 duplicateMovieClip (ins1, "mc"+i, i); this["mc" + i]._x = i; this["mc" + i]._y = i; }; for (i=1; i<=50; i++){// 클립 이동 this["mc_"+i]._x += 10; this["mc_"+i]._y += 10; }; for (i=1; i<=360; i++){ // 클립 삭제 this["mc" + i].removeMovieClip (); }; ---------------------------------------------------------------------------- setProperty ("mv", _x, 150); // mv 무비클립 x좌표 속성 변경 myMovieX = getProperty( mv, _x); // mv 무비클립 x좌표 속성 읽기 trace(myMovieX); ---------------------------------------------------------------------------- _alpha알파값(%) _currentframe 현재재생중인 프레임(#) _droptarget 드래그 앤드드롭 할때 놓는 타깃위치(name) _framesloaded 로드된 프레임수(#) _height 높이(#) _name 인스턴스(string) _rotation 회전값(#) _soundbuftime 사운드버퍼링 시간(기본값 5초:#) _totalframes총프레임수(#) _url다운로드한 URL(string) _visible보인다,안보인다 (true,false) _width가로길이(#) _xx좌표(#) _yy좌표(#) _xmouse 마우스x좌표(#) _ymouse 마우스y좌표(#) _xscale x배율(%) _yscale y배율(%) ---------------------------------------------------------------------------- _root.a.play;//메인에 있는 a무비클립프레임 재생 _root.a.stop;//메인에 있는 a무비클립프레임 중지 play();//stop으로 정지된 현재타임라인의 프레임 재생 stop();//현재타임라인의 프레임 중지 gotoAndPlay(1);//현재 Scene의 1프레임 재생 gotoAndPlay("a");//현재 Scene의 Label명 a 재생 gotoAndPlay("Scene 2", "c"); //Scene 2의 Label명 c 재생 a.gotoAndPlay(1);//a무비클립의 1프레임 재생 gotoAndStop(1);//현재 Scene의 1프레임 중지 nextScene(); //다음 장면의 프레임 1로 보내고 중지 prevSecne(); //이전 장면의 프레임 1로 보내고 중지 nextFrame(); //다음 프레임으로 보내고 중지 prevFrame(); //이전 프레임으로 보내고 중지 toggleHighQuality ();//저해상도와 고해상도 간을전환 updateAfterEvent();//화면을 갱신 (onClipEvent 핸들러 내에서만 사용) //(onMouseDown,onMouseUp,onMouseMove) ---------------------------------------------------------------------------- tellTarget ("../a") { nextFrame(); } //../a 무비클립을 호출후 다음 프레임 재생 if (_framesloaded = 10) {} // 만약 무비의 10프레임이 로드되면 ---------------------------------------------------------------------------- // with 문 for (i=0; i<1000; i++) { with (aaa[i]) { _x = Math.floor(Math.random() * 500); _y = random(500); _rotation = random(360); } } // tellTarget 문 (속도빠름) for (i=0; i<1000; i++) { tellTarget (aaa[i]) { _x = Math.floor(Math.random() * 500); _y = random(500); _rotation = random(360); } } ---------------------------------------------------------------------------- aaa = new Array();// 배열 초기화 aaa = new Array("1","2","3"); // 배열값 넣기 bbb = ["Sun","Mon","Tue"];// 배열값 넣기 aaa[1] = "abc"; // 배열값 변환( "2" 가 "abc" 로 변환) aaa[0] = "Jan" ;aaa[1] = "Feb" ;aaa[2] = "Mar" ; // 배열값 변환 aaa[3] = "Apr"// 배열 추가 (aaa 값은"Jan,Feb,Mar,Apr" ) ccc = aaa.concat(bbb);// 배열 합침 (ccc 값은"Jan,Feb,Mar,Apr,Sun,Mon,Tue" ) ddd = ccc.join("/");// ,를/로 변환(ddd 값은"Jan/Feb/Mar/Apr/Sun/Mon/Tue" ) ddd = ccc.length; // 배열값 갯수 (ddd 값은7 ) ddd = ccc.slice(2,4); // 배열값 읽기 (ddd 값은"Mar,Apr" ) eee = ccc.push("z","zz"); // 배열추가후배열값 갯수 (eee 값은9 ) //(ccc 값은 "Jan,Feb,Mar,Apr,Sun,Mon,Tue,z,zz" 로 변함) eee = ccc.pop();// 마지막 배열 분리후 값(eee 값은"zz" ) //(ccc 값은"Jan,Feb,Mar,Apr,Sun,Mon,Tue,z" 로 변함) eee = ccc.shift();// 첫번째 배열 분리후 값 (eee 값은"Jan" ) //(ccc 값은"Feb,Mar,Apr,Sun,Mon,Tue,z" 로 변함) eee = ccc.reverse();// 배열값 순서바꿈 (eee 값은"z,Tue,Mon,Sun,Apr,Mar,Feb" ) //(ccc 값도"z,Tue,Mon,Sun,Apr,Mar,Feb" 로 변함) eee = ccc.splice(2,5,"x","xx","xxx");// 배열값 읽기후변환(eee 값은"Mon,Sun,Apr,Mar,Feb" ) //(ccc 값은"z,Tue,x,xx,xxx" 로 변함) eee = ccc.unshift("1","2"); // 첫번째 배열추가후값(eee 값은"7" ) //(ccc 값은"1,2,z,Tue,x,xx,xxx" 로 변함) sss = new Array(1,2,3); // 숫자 배열값 넣기 uuu = sss.toString(); // 문자로변환.결과는 1,2,3 vvv = uuu.toLowerCase();// 대문자를소문자로 변환.원래 값은 변경되지 않음 vvv = uuu.toUpperCase();// 소문자를대문자로 변환.원래 값은 변경되지 않음 xxx = Number("111") //숫자로 변환. 결과는 111 xxx = Number("aaa") //숫자로 변환. 결과는 NaN xxx = Number(true)//숫자로 변환. 결과는 1 xxx = Number(false) //숫자로 변환. 결과는 0 ---------------------------------------------------------------------------- cliparray = new Array(); // 무비클립을 배열로 저장하기 for (a=1; a<=3; a++){ cliparray[a] =_root["clip"+a]; cliparray[a].x =_root["clip"+a]._x; cliparray[a].y =_root["clip"+a]._y; trace(cliparray[a].x); trace(cliparray[a].y); } ---------------------------------------------------------------------------- myString = new String(); // 문자 변수초기화 myString = new String("가나다"); // 문자 넣기 tet="가나다"; myString = new String(tet);// tet변수 넣기 text0=myString.charAt(0);// text0 값은 "가"-1개 읽기 text1=myString.charAt(1);// text1 값은 "나"-1개 읽기 text2=myString.charAt(2);// text2 값은 "다"-1개 읽기 text3=myString.concat("라마","바사","다"); // text3 값은 "가나다라마바사다"-추가 text4=text3.substr(2,4); // text4 값은 "다라마바"-여러개 읽기 text5=text3.substring(2,4);// text5 값은 "다라"-여러개 읽기 text6=text3.slice(2,4);// text6 값은 "다라"-여러개 읽기 text7=myString.charCodeAt(1);// text7 값은45208- 문자를 코드화 text8="a" + String.fromCharCode(64) + "m"; // text8 값은 "a@m"- 코드를 문자화 text9= text3.indexOf("다");// text9 값은 2-문자위치 text10= text3.lastIndexOf("다"); // text10 값은 7-마지막 문자위치 text11= text3.length;// text11 값은 8-문자길이 text12= text3.split("나"); // text12 값은 "가,다라마바사다"-문자분리 text13= text6.concat(text3); // text13 값은 "다라가나다라마바사다"-문자합침 text14= text13.substr((text13.length-1),1);// text14 값은 "다"-마지막 문자 읽기 sss = myDate.toString();day = sss.substring(0,3); // 문자로변환 ---------------------------------------------------------------------------- // aaa 문장을 bbb 배열로 저장하기// 문장을 배열로 저장하기 // 결과는 bbb[0]="a" bbb[1]="b" bbb[2]="c" bbb[3]="d" bbb[4]="e" aaa = "a b c d e"; aaalen = aaa.length; bbb = new Array(); for (a=0; a<=aaalen; a++){ bbb[a] = "";}; bbbno = 0; bbbchr = ""; for (a=0; a<=aaalen; a++){ if ( aaa.charAt(a) == " " ) {bbb[bbbno] = bbbchr; bbbno += 1; bbbchr = ""; } else { bbbchr += aaa.charAt(a); }; }; for (a=0; a<=bbbno; a++){trace( "*" + bbb[a] + "*" ) }; ---------------------------------------------------------------------------- for (a=1; a<=22; a++) { // 텍스트 필드 글자속성 this["k"+(a)].textColor=0xff0000; this["k"+(a)].border=true; this["k"+(a)].borderColor=0xff0000; this["k"+(a)].background=true; this["k"+(a)].backgroundColor=0xffffff; }; ---------------------------------------------------------------------------- TextField.removeTextField(); // 텍스트 필드 삭제 ---------------------------------------------------------------------------- createTextField ("instanceName", depth, x, y, width, height) // 텍스트 필드 생성 instanceName 새 텍스트 필드의 인스턴스 이름 depth 새 텍스트 필드의 깊이를 지정하는 양의 정수 (2 는 1를screen over) x 새 텍스트 필드의 x 좌표를 지정하는 정수 y 새 텍스트 필드의 y 좌표를 지정하는 정수 width 새 텍스트 필드의 넓이를 지정하는 양의 정수 height 새 텍스트 필드의 높이를 지정하는 양의 정수 instanceName.type = "dynamic"; // 텍스트 필드의 기본 속성(dynamic 또는 input) instanceName.autoSize = "false"; // (글자수에 맞게 테두리 크기 자동 조절 true false center right) instanceName.border = false; // (테두리) instanceName.borderColor = 0xff0000; // (테두리 색상) instanceName.background = false; // (배경) instanceName.backgroundColor=0xffffff; // (배경 색상) instanceName.textColor = 0xff0000; // (글자 색상) instanceName.multiline = false;// (한줄또는여러줄) instanceName.selectable = true;// (텍스트 필드를 선택할 수 있는지 여부) instanceName.maxChars = null;// (사용자가 입력할 수 있는 최대 문자 수) (null 이면 무한대) instanceName.length = 0; // (글자 수) instanceName._name = ""; // (인스턴스 이름) instanceName.variable = "";// (변수 이름) instanceName.html = false; // (html 태그 사용 여부) instanceName.htmlText = "";// (html 태그) instanceName.wordWrap = tr |
| [C#]마우스 좌표 얻기 (0) | 2009.04.08 |
|---|---|
| EVC 4.0 프로그래밍의 준비 (0) | 2009.04.06 |
| Introduction to Programming with Managed DirectX 9.0 (0) | 2009.03.09 |
| DirectX Programming in C# (0) | 2009.03.09 |
| 윈도우 PHP Web Programming (14) - PHP 문자열 함수 (0) | 2009.03.06 |
The industry standard 3D API, OpenGL, is not the only 3D API that you can use on the .NET platform in the Microsoft Windows environment. Another choice is DirectX, which has been steadily increasing its functionality, stability, and market share among developers writing all sorts of Windows multimedia software, games, and other applications that make use of 2D and 3D graphics. While earlier versions of DirectX often left a lot to be desired, its latest incarnation, DirectX 9.0, is a serious product worth a longer look, especially if you want to target multiple Microsoft platforms: Microsoft Windows, PocketPC, or X-Box.
With DirectX 9.0, you have a choice of two 3D APIs on the Microsoft Windows platform, but that doesn't mean that it must be one or the other. Even if you stay with the OpenGL for 3D API (it's an industry standard after all, and there's a lot of information and talent to draw upon) you may still need DirectX's other components that you will simply not find in OpenGL. Direct3DX is only a part of the DirectX puzzle, and other pieces are equally interesting. If you have never considered using DirectX before, the following summary will give you a better view of what's in store:
Just like OpenGL, DirectX too used to be aimed at developers coding in C/C++. That's natural, because compiled C/C++ code is faster than interpreted Visual Basic. However, Microsoft knows that in order to make .NET a success, they need to attract as many developers as they can. To do that, all of their crucial APIs must be available in managed form, so they can be easily incorporated into applications written in C#, Visual Basic .NET, and other .NET languages.
The recently released DirectX 9.0 SDK is a clear sign that Microsoft wants to broaden the use of DirectX among developers who do not speak C++ and MFC programmers. The official release of the DirectX 9.0 SDK is available in three forms:
The managed versions (for C# or VB.NET) can also be used in Visual C++ (when writing managed code), and JScript .NET applications. Other languages available for the .NET platform ought to be able to make use of them, as well. This lowers the barrier of entry for those programmers who code in C# or VB .NET for a living, and could potentially lead to some interesting software titles appearing on the market.
Starting managed DirectX 9.0 development is quite inexpensive; if you do not need the visual tools, you can get by with the free SDKs. But you would really be doing yourself a disservice if you did not use the Visual development products, as they really help developers manage their work better and work more efficiently.
Here's the list of tools you need to start coding with DirectX 9.0:
Despite their best efforts to provide managed versions of the whole of DirectX, Microsoft does not (yet) provide managed versions of DirectMusic, DirectShow, or DirectSetup. One additional component that you will find is a basic support for audio and video playback.
While all components listed earlier in this article behave quite reasonably during installation, DirectX 9.0 SDK is a bit temperamental and may waste some of your time, if you let it. The following tips should help you avoid wasting time.
If you haven't already done so, update your Windows system with the latest patches from Microsoft. Next, download the latest release of the .NET Framework SDK, install it, and check for updates with Windows Update and manually, in MSDN's .NET Framework section. Now you can download your choice of the DirectX 9.0 SDK versions (full, C#, or VB.NET) and double-click on it to unpack the installation files to a temporary directory.
When you run setup, it will ask you for a path to install the SDK. There is a bug in the installer that, in some cases, does not accept the path you choose when you click on the Browse button. If the problem persists and you cannot force the installer to obey you, the solution to this problem is to quit the setup, remove temporary files, unpack the archive again, and then, when the installer asks for the path, change C:\DXSDK to a different path (e.g., E:\DXSDK) manually, by typing it into the Path text field.
Another strange thing that you might run into is a problem with DLL locations. The DirectX DLLs are put into the C:\WINDOWS\assembly\GAC directory, where they are essentially inaccessible to your development environment, be it Visual C# or Visual Basic .NET. It doesn't always happen, but if you open a sample project from the DirectX 9.0 SDK and you see exclamation marks in the References list next to Microsoft.DirectX libraries, then that's the sign of this particular installer misbehavior. Fortunately, it is very easy to fix this problem. Simply open the command line (console) window and type:
cd c:\windows\assembly\gacdirand you should see this:
Microsoft.DirectXMicrosoft.DirectX.AudioVideoPlaybackMicrosoft.DirectX.DiagnosticsMicrosoft.DirectX.Direct3DMicrosoft.DirectX.Direct3DXMicrosoft.DirectX.DirectDrawMicrosoft.DirectX.DirectInputMicrosoft.DirectX.DirectPlayMicrosoft.DirectX.DirectSoundThe DLLs we are looking for are located in subdirectories with long names like:
Microsoft.DirectX.Direct3D\1.0.900.31bf3856ad364e35\ Microsoft.DirectX.Direct3D.dllCreate a normal folder in your chosen location and copy each DLL to it. Then, update the References in your project and Build a sample application. Everything should work fine now.
Note: If you downloaded the DirectX 9.0 Redistributable, do not install it, but keep it on CD-R until you have your application ready for distribution. It contains files that Microsoft lets developers distribute to end users, and is of not much use to programmers. It's the same story with the NET Framework Redistributable.
Programming with Managed DirectX 9.0 is currently a somewhat unexplored territory, and you will need a good guide to help you along. Your first resource will be various places on the Web and the C/C++ code in the SDK itself. Good books on this subject are yet to appear, but that should not be the case for too long.
Note that programming with Managed DirectX 9.0 is something that you should attempt after you master programming C# or VB.NET, or you will find it a frustrating experience. O'Reilly has published very good books on this subject: .NET Framework Essentials, .NET Windows Forms in a Nutshell, C# Essentials, and VB.NET Language in a Nutshell ought to be your essential reading if you are new to .NET.
To get a better understanding of computer graphics, get a copy of Computer Graphics: Principles and Practice in C or Computer Graphics. Also, the Cg Tutorial is an excellent introduction to the world of real-time shader programming techniques.
If you want to get deep into the subject, consider SIGGRAPH membership. It is an inexpensive way to gain access to a vast library of SIGGRAPH proceedings, which are a goldmine of ideas.
Happy coding!
Jacek Artymiak started his adventure with computers in 1986 with Sinclair ZX Spectrum. He's been using various commercial and Open Source Unix systems since 1991. Today, Jacek runs devGuide.net, writes and teaches about Open Source software and security, and tries to make things happen.
Return to ONDotnet.com
Showing messages 1 through 3 of 3.
Book URLs| EVC 4.0 프로그래밍의 준비 (0) | 2009.04.06 |
|---|---|
| 액션 스크립트 용어 및 정리 (0) | 2009.03.17 |
| DirectX Programming in C# (0) | 2009.03.09 |
| 윈도우 PHP Web Programming (14) - PHP 문자열 함수 (0) | 2009.03.06 |
| OS/2 warp 4 on virtual box (0) | 2009.03.05 |