posted by 권오성의 Biomedical Engineering 2011. 2. 16. 09:45
골든이나 토드로 돌리고 프로그램에 옮길 땐 ; 를 빼주어야 한다.

실수를 반복하지 않도록 주의하자!!
posted by 권오성의 Biomedical Engineering 2010. 12. 29. 19:16

서버관리자를 열고 보안정보에 보면 "IE ESC 구성" 이 있습니다. 여기서 관리자 또는 사용자에 대해서 "보안강화구성" 을 해제 할 수 있습니다. 이렇게만 해도 일반적으로 인터넷 사용을 하는데에는 문제가 없습니다만, 더 낮추려하거나 내맘대로 설정하기를 원한다면 레지스트리 수정이 필요합니다.

레지스트리 수정은 아래와 같습니다.

HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3
으로 가셔서 "MinLevel" 의 16진수 값을 조정하시면 됩니다.

예: "MinLevel" 을 11000 으로 고치면 위의 이미지의 선택할 수 있는 보안 수준은 "보통" 까지만 나옴.

최소 10000
낮음 10500
보통 11000
약간높음 11500
높음 12000

나머지도 레지스트리에서 조절이 가능하지만 "MinLevel" 값만 regedit 를 이용해서 고치시고 나머지 조절은 익스플로러의 도구>옵션 에서 조정하시기 바랍니다.

이 팁은 서버 윈도우 사용시 잘못 설치되거나 하는 등의 이유로 "높음" 하나만 나오거나 아예 조절이 불가능하는 등의 설정에 곤란을 겪을 때 해결할 수 있습니다.

posted by 써니루루 2008. 3. 26. 09:21

출처 : http://monac.egloos.com/1252483


자바스크립트와 첫 인연을 맺은 것은 1996년도인데, 진지하게 사용하는 일이 없기 때문에 계속해서 까먹기만 하는 유명한 언어로 인식되어 있는 중.

자바스크립트를 보면 금방 또 알지만 항상 잊어버리기 때문에 언제든지 새로운 기억을 주입시키기 위한 용도로 작성함. 게다가, 잘 정리된 형태의 글을 보기 힘들고, 내 입맛에 맞는 글을 보기 힘들기 때문에 내 입맛에 맞게 정리한다는 목적 + 다른 분들도 참고할 분은 참고가 되었으면 해서 정리함. 특히, Ajax 프로그래밍과 함께 다시 뜨고 있는 자바스크립트 때문에 괴로운 분들에게 도움이 되길.

자바스크립트는 HTML 페이지에 저장하고

<script type="text/javascript" language="javascript">
  여기에 자바스크립트 코드 추가
</script>

하는 형태면 되지만 불편함이 많으니 "자바스크립트 학습 환경 만들기(http://monac.egloos.com/1222893)"를 참고해서 환경을 만들어서 사용하시면 편함.


1. 경고 보여주기

window.alert( 'Hello, world' );

alert( 'Hello, world' );

두 가지가 다 가능한 형식. 자바스크립트는 언제 어디서나 참조할 수 있는 내장 객체를 갖고 있는 데 그 중에 하나가 window 객체로 우리가 보는 창과 관련된 모든 기능을 제공함. 그 중에 대표적인 것이 경고창 띄우기.


링크를 클릭했을 때, "정말 삭제할래?"등의 대화상자를 보여주고, yes/no 답변을 묻는 confirm() 함수도 마찬가지.

<a href="#" onclick="return confirm( "정말 날 떠날거야?")">click</a>
<a href="#" onclick="return window.confirm( "정말 날 떠날거야?")">click</a>

confirm(), window.confirm() 모두 동일. 그러니까, window 객체에 속한 함수들은 window라는 이름을 생략하고 사용할 수 있음.

사용자로부터 입력을 받는 예로는 prompt( "나이를 알려줘" ) 라든가, window.prompt( "나이를 알려줘" ) 라든가 하는 형태가 가능.


2. 변수

i = 0;
alert( i );

변수를 위해 특별히 선언하지 않고 사용해도 잘 되지만 보통은 var 키워드를 사용해서 변수를 사용하는 것을 선호하고 있고, 대부분의 Ajax 라이브러리들도 var 키워드를 사용해서 변수를 선언해서 사용하고 있음. 명시적으로 변수를 선언해서 사용하는 것이 더 좋다고 생각함.

var i = 0;
i = "hello world";
i = false;

스크립트 언어들은 C/C++/Java 같은 언어들과 달리 데이터 타입이 없는 경우가 대부분이며, 이는 프로그래밍을 간단하게 해준다는 장점이 있음.
그렇다고 해서, 실제로 데이터 타입이 없다거나 구분하지 않는 것은 아니며 내부적으로 데이터 타입을 갖고 있으며, 그에 따라 적절하게 알아서 동작하는 똑똑한 기능을 갖추고 있음. 그래서, 위와 같은 코드를 사용할 경우 알아서 데이터 타입을 변환하고, 알아서 동작함. 내부적으로 갖는 데이터타입을 서브 데이터 타입(sub data type)이라 함. 신경 안써도 됨. 이런 게 있으면 좋다라는 정도의 상식으로만 알고 있으면 되고, 이런 것 모르는 스크립터가 대부분이니 사는 데 지장없음!

첫번째는 정수형이고, 두번째는 문자열 형식이고, 세번째는 불리언(boolean) 형식임.

true/false는 자바스크립트 내부에서 지원하는 키워드. 진리값이니 뭐니 말은 많으나 다 필요없음. 참이면 참이고, 거짓이면 거짓임.

문자열은 "과 ' 모두 사용할 수 있는데, HTML에서 사용할 때는 HTML의 name="value"와 혼동되므로 '를 사용하는 것이 보통임.


3. 배열

var days = new Array( "Mon", "Tue", "Wed" );
days[3] = "Thu";

alert( days );

배열은 Array 클래스를 이용해서 선언함. 클래스 생성은 다른 언어들처럼 new 키워드를 사용함. 배열의 인덱스는 0 부터 세기 시작하는데, 위와 같이 초기값으로 3개의 요소를 주면 0, 1, 2 번째에 할당되고, 3번째에 새로운 요소를 할당하는 것도 자유로움.

배열 자체가 동적이니까 마음대로 편안하게 사용할 수 있음. 즉, 마음대로 꼬장부리면서 사용할 수 있다는 의미.

var days = new Array( "Mon", "Tue", "Wed" );

days[5] = "Thu";

alert( days );

이렇게 쓰면 중간에 비는 것들은 전부 비게되고, 5번째에 삽입이 됨. 꼬장은 그대의 자유.

new Array() 라고 안 쓰고 싶다면

var days = [ "Mon", "Tue" ];
days[2] = "Wed";
alert( days );

와 같이 사용할 수 있음.


4. 제어 구조

var rand = Math.random();
rand = Math.ceil( 6 * rand );

if( rand % 2 == 1 )
{
  alert( 'odd' );
}
else
{
  alert( 'even' );
}

Math 클래스에서는 다양한 수학함수들과 난수 생성을 할 수 있음. Math.cos(), Math.abs(), Math.sqrt() 등이 준비되어 있음.

다른 언어들처럼 if 구조는 축약형을 사용할 수 있음.

var output = (rand % 2 == 1 ) ? 'odd' : 'even';

alert( output );



4.1 swtich

switch ... case 구조도 물론 지원함.

var rand = Math.random();
rand = Math.ceil( rand * 6 );

switch( rand )
{
  case 1:
  case 3:
  case 5:
    alert( 'odd' );
  default:
    alert( 'even' );
}


5. 루프

일반적인 for, while을 모두 지원하며 사용법도 동일함.

var days = ["Mon", "Tue", "Wed", "Sun" ];  // 일주일이 4일 뿐이라서 3일 일하면 노는 세상을 꿈꾸는 무의식의 반영

for( var ctr = 0; ctr < days.length; ++ctr )
{
  alert( days[ctr] );
}

foreach와 비슷한 for .. in 구조는 다음과 같음

var days = [ "Mon", "Tue", "Wed" ];

for( var day in days )
{
  alert( days[ day ] );
}


while 문은 다음과 같음

var days = [ "Mon", "Tue", "Wed" ];

var ctr = 0;

while( ctr < days.length )
{
  alert( days[ ctr ] );
  ++ctr;
}



6. 정규표현식

function html_escape( str )
{
  return str.replace( /&/g, "&amp;" ).replace( /</g, "&lt;" ).replace( />/g, "&gt;" ).replace( /"/g, "&quot;" ).replace( /'/g, "&apos;" );
}

함수는 function 키워드로 선언하면 되고, 데이터 타입이 없으니까 반환 타입 지정 같은 것도 없음.
정규표현식은 어떤 문자열이든 점(.) 찍고 replace() 메서드를 호출하면 됨.

"Hello World".replace( /Hello/, "Cruel");

alert(  "Hello World".replace( /Hello/, "Cruel")   );   // 원래 세상은 잔인햇!!!!

객체지향 언어적인 특성도 갖고 있기 때문에 위에처럼 메서드 연쇄로 쭈욱 호출하면서 처리해도 됨.

위에 코드는 HTML로 쓰인 것들을 안전한 문자열로 변환하기 위해 만든 자바스크립트 함수. 다음 코드로 결과 확인

alert( html_espcae( "<HTML>" ) );



6.1 함수 가변 인자

function make_list()
{
  var ctr = 0;

  for( ctr = 0; ctr < arguments.length; ++ctr )
  {
    alert( arguments[ctr] );
  }
}

make_list( "Mon", "Tue", "Wed" );

함수의 인자는 arguments 내장 객체로 전달되므로 이를 이용해서 처리.



7. 이벤트

자바스크립트는 몇가지 이벤트들을 정의하고 있음. 대표적인 것이 onload 이벤트로 페이지가 로딩될 때 실행하는 처리들을 이곳에서 할 수 있음.

<body onload="alert( 'Hahaha' );" >

이벤트에 직접 자바스크립트를 쓰는 것도 가능하고, 함수 이름을 지정하는 것도 가능함.

function init()
{
  alert( '오빠왔다!!' );
}

window.onload = init;

body 태그에 쓰는 것도 창과 관련된 것이므로 window 객체의 onload 이벤트에 해당 함수 이름을 지정함. init 뒤에 ()를 붙이지 않음. C언어처럼 말하자면 함수의 주소만 지정하는 것이므로.

자바스크립트는 함수 이름을 지정하지 않아도 되니까 위 코드를 다음과 같이 하나로 합치는 것이 가능함.

window.onload = function() {
  alert( '오빠왔대두!!!' );
}

init 함수 정의해서 init만 삭제하고, 합쳐놓은 것과 똑같은 것을 알 수 있음.

인자가 있는 함수를 정의한다면

window.onload = function( a, b ) {
  alert( a + b );
  alert( "오빠 다녀갔어~~!" );
}


8. 클래스

자바스크립트는 객체지향 언어의 특성도 갖고 있음.(다소 부족한 기능이지만)
자바스크립트는 클래스를 위한 키워드가 존재하지 않음. 그냥 클래스도 함수임.

객체지향 언어에서 생성자를 정의한다고 하는데, 사실상 생성자라는 것이 "()" 함수를 정의하는 것이라 할 수 있음.
인자가 있는 생성자라면 "(a, b)"를 정의하는 것이라 할 수 있고.

예를 들어, C++을 보면

size_t length(0);
string arg1( ARGV[1] ), arg2( ARGV[2] );

이런식으로 변수를 선언할 수 있는 것도 생성자의 "()"이 함수이기 때문.

자바스크립트에서 클래스는 함수로 정의함.


function Character( name, gender )
{
  var _name = name;
  var _gender = gender;


  this.get_name = function() { return _name; }
  this.set_name = function(value) { _name = value; }


  this.get_gender = function() { return _gender; }
  this.set_gender = function(value) { _gender = value; }


  this.toString = function() { return _name + ":" + _gender  }
}

var nadia = new Character( "Nadia" );
nadia.set_gender( "F" );

alert( nadia.get_name() );
alert( nadia.get_gender() );

alert( nadia.toString() );

new 키워드로 인스턴스를 생성할 때, 함수의 인자 수를 정확하게 맞추지 않아도 된다는 것.

클래스 정의의 대부분은 이처럼 함수를 직접 선언하는 형태로 구현됨.

이처럼 함수에 이름을 주지 않고, 마음 내키는 대로 함수를 남발하는 것을 익명 함수(Anonymous function or Anonymous method)라 부름. 굳이 기억할 필요없는 함수들은 이름을 주지 않고, 관리를 편하게 하자는 나름대로의 합리적인 이유가 있음.

this 키워드는 현재 인스턴스를 가리키기 위해 사용되는 것으로 다른 객체지향 언어들과 쓰임이 동일함.

자바스크립트에도 루비와 마찬가지로 eval() 이라는 함수가 존재해서 문자열을 코드로 해석하게 하는 기능이 있음.

eval( "alert( 3 + 5 )" );

을 실행하면

alert( 3 + 5 );

가 되어 결과 8이 출력되는 것을 볼 수 있음.

루비의 class_eval(http://monac.egloos.com/1158938)에서 보면 class_eval() 함수를 사용해서 클래스 멤버에 대한 get/set 메서드를 자동으로 생성하는 기능을 구현하는 것을 설명한 적이 있고, 실제 루비의 attr_accessor 키워드가 이렇게 구현되어 있는데, 자바스크립트도 eval() 함수가 있기 때문에 이와 같은 구현을 하는 것이 가능함.

class Person
    attr_accessor :name
end

루비는 이렇게 해주면 name에 대한 getter/setter가 모두 자동으로 만들어지니까 간편하다는 이야기들을 자주하는데, 자바스크립트는 이 보다 더 황당하게 간단함.(한 줄!)
자바스크립트에서 루비처럼 attr_accessor 키워드를 제공하는 것은 아니지만 나중에 소개할 Extjs 같은 Ajax 프레임워크들은 eval을 적극 활용해서 그런 기능을 대부분 자체적으로 만들어서 사용하고 있음.



9. document 객체

document 객체는 웹브라우저에서 문서와 관련된 모든 요소들을 관리함.

document.embeds 배열은 <embed> 태그로 선언된 모든 요소들의 목록을 갖고 있음.

document.forms 배열은 <form> 태그로 선언된 모든 요소들의 목록을 갖고 있음.

document.frames, document.images, document.links 배열이 있음.

<form>
  <input type='text' name='text1' />
</form>

이 경우 text1 텍스트박스에 접근하려면

alert( document.forms[0].elements[ 'text1' ].value );

텍스트 상자의 값을 출력하게 됨. 첫번째 폼이기 때문에 forms[0]로 지정한 것임.

<form name='my_form'> 으로 선언되어 있다면

document.forms[ 'my_form' ].elements[ 'text1' ].value

와 같은 형식으로도 접근 가능함.

<script>
function showme( f )
{
  alert( f.elements[ 'text1' ].value );
}
</script>

<form name='my_form' >
  <input type='text' name='text1' />
  <input type='button' onclick='showme( this.form );' />
</form>

함수 인자에서 this.form으로 폼에 대한 참조를 넘겼음. this.form은 document.forms[ 'my_form' ]과 의미가 같음.

document.forms[ 'my_form' ].elements[ 'text1' ].value 를

f.elements['text1'].value 로 축약한 것임. f는 함수에 전달된 인자.

checkbox, radio 버튼은 checked 속성이 true/false로 지정

select로 표현하는 드랍다운리스트는 selectedIndex로 인덱스를 가져올 수 있음.
option은 selected와 value 멤버로 접근함.


웹페이지에서 컨트롤을 찾는 방법은 documents.forms... 복잡하게 찾아가는 방법도 있지만,  document.getElementById()를 쓰는 방법도 있음.



<script>
function showme( f )
{
  var label = document.getElementById( 'label1' );
  label.innerHTML = html_escape( f.elements['text1'].value );
}
</script>

<form name='my_form' >
  <input type='text' name='text1' />
  <input type='button' onclick='showme( this.form );' />
</form>

<span id='label1'>---</span>


html_escape() 함수는 위에 정의한 것을 사용.


getElementById()는 전체 컨트롤을 전부 탐색하기 때문에 느리다는 것을 명심해야 하고, 화면에 컨트롤이 많다면 성능저하의 주범이 될 수 있으므로 조심해서 사용해야 함. ASP.NET 같은 언어는 Page.FindControl() 메서드로 컨트롤을 탐색하는 데, 이것도 역시 이와 마찬가지.


10. DOM 처리

DOM은 Document Object Model의 약자. 문서 객체 모델이라는 데, 문서의 각 구성 요소 전부를 트리 구조 형태로 표현하는 것.

getElementById() 함수도 바로 이 DOM 트리를 탐색하는 것임. FireFox에서도 Web Developer 플러그인을 설치하면 DOM Inspector를 통해 DOM 트리를 볼 수 있음.

getElementsByTagName( name )

태그 이름으로 해당 요소 검색하는 것. 근데, 웹 페이지에 P 태그가 얼마나 많이 쓰이겠나. 그러니까, 반환 타입은 배열형식임.

var p = document.getElementsByTagName( 'p' )[0];

뒤에 [0]이면 첫번째 p 태그를 가져올 수 있음.

var p_arr = document.getElementsByTagName( 'p' );   // 배열로 가져오기

createElement( name )

DOM 트리에 새로운 요소 만들기.

createAttribute( name )

새로운 속성 만들기... name="value"로 되는 특성에서 name  만들기.

createTextNode( name )
  name을 키로 하고, 텍스트를 값으로 갖는 노드 만들기.

appendChild( node )
  현재 요소를 node에 자식으로 추가하기. 그러니까, 어느날 갑자기 node에겐 딸린 자식이 생긴다는 의미...;;


<script>
function show( f )
{
  var p = document.getElementsByTagName( 'p' )[0];
  var label = document.createElement( 'span' );
  var text = document.createTextNode( f.elements['text1'].value );
 
  label.appendChild( text );
  p.appendChild( label );
}
</script>

<form>
  <input type="text" name="text1" />
  <input type="button" value="show text" onclick="show(this.form);" />
  <p>Entered Text: </p>
</form>

p.innerHTML을 사용하면 내용을 바꾸는 게 되지만 appendChild()를 썼기 때문에 내용이 추가되는 형태가 되었음.

DOM 트리 구조를 보면 이해하기 쉬우므로 DOM Inspector 사용을 권함.

===== 기본적인 명령들 =====
1. 간단하게 팝업창 두개 띄우기 [참고로 (main.html)안에서 모두 작성한 것임..]
<HEAD>
<script language="javascript">
 function recruit()  //채용공고 팝업을 띄울때
 {
  window.open("/recruit.htm","new1","width=507 height=680");
 }

 function initiate()  //공지사항 팝업을 띄울때.
 {
  window.open("/initiate.htm","new2","width=680 height=420");
 }

 function mypop() //두개의 팝업을 썩기..
 {
  window.open("/recruit.htm","new1","width=507 height=680");
  window.open("/initiate.htm","new2","width=680 height=420");
 }
</script>
</HEAD>

// onload는 페이지 로드 시 팝업 띄우기.
// onunload는 페이지 닫힐 때 팝업 띄우기.
<BODY onload="mypop()" onunload="recruit()">  //여기에서 스크립트 함수 호출

Tip. 만약 팝업창을 클릭하면 닫히게 하고 싶다면 이 명령을 추가...
<img src="파일.htm" onClick="window.close()">


//팝업창 닫히면서 페이지 이동
<script Language="JavaScript">
function golistview()
{
var firstWin = window.opener;
firstWin.location.href="Index.asp";
window.close(this);
}
</script>

<a href="javascript:golistview()"><img src="/Images/but_list.gif" border="0" name="but_list"></a>

posted by 권오성의 Biomedical Engineering 2007. 11. 26. 14:38
레이어와 <DIV>태그

LAYER(레이어)는 겹치게 표현하기 위해서 원하는 위치에<DIV>태그로 넣는것이며,
DIV 태그는 문단의 정렬보다는 좌표의 개념입니다
해상도에 따라 오른쪽 끝이 0 - 800 되기도 하고 0 - 1024가 되기도 합니다.

[형식]

<DIV ID="layer숫자(1.2.3......)" Style="position:absolute; left:y값; top:x값; width:넓이;height:높이;Z-index:2;">


left는 좌측으로 부터의 거리 (px단위)
top는 상단으로 부터의 거리 (px단위)
레이어의 크기는 width. height로 지정하고,
지정하지 않으면 레이어에 사용되는 이미지.텍스트의 크기만큼 지정됩니다.

★. ID속성은 자바스크립트나 head부에 정의된 css와 연결할때 사용하며, 독립적으로 사용할 때는 생략할수 있습니다.

즉 <DIV style="position:absolute; left:200; top:90;;Z-index:12;">이렇게 사용해도 됩니다.

★.여기서 <DIV>는 전체위치를 표시해 주기 때문에 문서중의 어떤 위치에 넣어도 상관 없습니다.

* 그림을 넣을 때 *

<DIV style="position:absolute; left:200; top:90;Z-index:2;"> <img src="images/.....jpg"></DIV>


[용어설명]

position:absolute : 위치값으로 left나 top을 지정.
Z-index : 레이어의 순서를 지정.(숫자가 클수록 위로 올라갑니다)
margin : 레이어의 바깥 여백값으로 위쪽 .좌측의 여백순으로 지정(margin:0px,15px)
background-image : 레이어의 배경으로url(파일명)을 지정해 줍니다.

정리하면

글과 이미지를 <DIV>를 사용하면 다른 배경이미지와 상관없이 브라우저창에 별도로 나타나 납니다.
그런데 이미지와 글에 DIV태그를 같이 사용했을 때 글을 이미지 위에 올리려면 이미지 보다 글의 레이어 숫자를 크게합니다.

Z-index:2. Z-index:1이 있다면 Z-index:2가 위에 위치합니다.

주의: 카페에 올릴때나 메일로 보낼때 보는사람의 해상도가 각기 다르기 때문에 주의하셔야 합니다.

지금까지 설명한것의 사용예

<div id="layer1" style="width:400px; height:400px; position:absolute; left:350px; top:570px; z-index:2;">글쓰는 곳 </div>
<div id="layer2" style="width:1px; height:416px; position:absolute; left:200px; top:400px; z-index:1;"> <img src="이미지 주소(URL)></div>

SAYA 올림
posted by 권오성의 Biomedical Engineering 2007. 10. 31. 17:33
이 문제때문에 하루종일 헤맷네요.

이건 라이센스가 있는 상용컴포넌트를 사용했을 때의 기록이 남아서입니다.

이 라이센스 부분을 모조리 삭제하시면 해결됩니다.

\Properties 밑에 "licenses.licx"에 들어있는 정보를 모조리 삭제합니다.

and then... 빌드합니다. ^^
posted by 권오성의 Biomedical Engineering 2007. 10. 10. 11:25
사용자 삽입 이미지

입사 후 웹관련 분야에서 일하고 싶었는데 본의 아니게 임베디드 장비 개발회사로 취업하여 장비와 맞물린 개발업무를 하고 있습니다.
'C#은 웹 전문언어야~'라고 생각하고 있었는데 얼마전 VOIP, IPTV 개발회사를 방문해보니 의외로 C#으로 개발하고 있는 회사가 많다는걸 알게 되었습니다. 특히 젊은 사장의 경우 말입니다.
다시 한번 C#의 무궁무진한 개발분야를 염두해 두시라고 올려봅니다.
posted by 권오성의 Biomedical Engineering 2007. 9. 20. 10:26
FlexGrid Insert/Remove Example
 
SUMMARY
 
이번에는 FlexGrid에서 특정 위치에 칼럼을 삽입하거나 삭제하는 방법을 배워볼 것이다. 엑셀에서 칼럼을 추가하거나 삭제할 때의 방식과 비슷하도록 하기 위해 고정행 위에서 마우스 오른쪽 버튼을 클릭할 때 팝업 메뉴를 표시한 후 처리하도록 구성했다(아래 그림 참조). 추가가 가능한 칼럼은 과목 칼럼으로 한정한다.
사용자 삽입 이미지


 




BASIS

이 예제를 완성하려면 비주얼 베이직에서 팝업 메뉴를 표시하는 방법과 FlexGrid에서 칼럼을 추가하거나 삭제하는 간단한 방법에 대해 알아야 한다. 당연하게도(^^).... 참고문헌 [1], [2]에서 각 방법에 대한 친절한 설명을 찾을 수 있었다. 아래에 퍼왔으니 참고하시길...
 
 
Pop-Up Menus (참고문헌 [2]에서 가져왔음)

Visual Basic also supports pop-up menus, those context-sensitive menus that most commercial applications show when you right-click on an user interface object. In Visual Basic, you can display a pop-up menu by calling the form's PopupMenu method, typically from within the MouseDown event procedure of the object:
 
Private Sub List1_MouseDown(Button As Integer, Shift As Integer, _
        X As Single, Y As Single)
    If Button And vbRightButton Then
        ' User right-clicked the list box.
        PopupMenu mnuListPopup
    End If
End Sub

The argument you pass to the PopupMenu method is the name of a menu that you have defined using the Menu Editor. This might be either a submenu that you can reach using the regular menu structure or a submenu that's intended to work only as a pop-up menu. In the latter case, you should create it as a top-level menu in the Menu Editor and then set its Visible attribute to False. If your program includes many pop-up menus, you might find it convenient to add one invisible top-level entry and then add all the pop-up menus below it. (In this case, you don't need to make each individual item invisible.) The complete syntax of the PopupMenu method is quite complex:
 
PopupMenu Menu, [Flags], [X], [Y], [DefaultMenu]
 

By default, pop-up menus appear left aligned on the mouse cursor, and even if you use a right-click to invoke the menu you can select a command only with the left button. You can change these defaults using the Flags argument. The following constants control the alignment: 0-vbPopupMenuLeftAlign (default), 4-vbPopupMenuCenterAlign, and 8-vbPopupMenuRightAlign. The following constants determine which buttons are active during menu operations: 0-vbPopupMenuLeftButton (default) and 2-vbPopupMenuRightButton. For example, I always use the latter because I find it natural to select a command with the right button since it's already pressed when the menu appears:
 

PopupMenu mnuListPopup, vbPopupMenuRightButton
 

The x and y arguments, if specified, make the menu appear in a particular position on the form, rather than at mouse coordinates. The last optional argument is the name of the menu that's the default item for the pop-up menu. This item will be displayed in boldface. This argument has only a visual effect; If you want to offer a default menu item, you must write code in the MouseDown event procedure to trap double-clicks with the right button.
 
 
 
ColPosition Property
Moves a given column to a new position.
 
Syntax
[form!]vsFlexGrid.ColPosition(Col As Long)[ = NewPosition As Long ]
 
Remarks
The Col and NewPosition parameters must be valid column indices (in the range 0 to Cols - 1), or an error will be generated.
When a column or row is moved with ColPosition or RowPosition, all formatting information moves
with it, including width, height, alignment, colors, fonts, etc. To move text only, use the Clip property instead.
The ColPosition property gives you programmatic control over the column order. You may also use the ExplorerBar property to allow users to move columns with the mouse.
 
 
IMPLEMENTATION
 
팝업 메뉴를 표시하는 이벤트로 MouseUp을 선택했다. 일단 마우스 오른쪽 버튼을 눌렀는지 확인한 후 다음으로 과목명 칼럼을 클릭했는지 확인한다. 두가지 조건을 모두 만족하면 엑셀의 동작방식과 비슷한 효과를 주기 위해 해당 칼럼을 모두 선택 상태로 만들고 팝업 메뉴를 표시한다.
 
Private Sub FG_MouseUp(Button As Integer, Shift As Integer, _
                       X As Single, Y As Single)
    If Button And vbRightButton Then
        '
과목명 셀을 클릭할 때만 팝업 메뉴를 표시한다.
        If (FG.MouseRow = 1) And (FG.MouseCol > 1) And (FG.MouseCol < FG.Cols - 2) Then
            '
선택한 느낌이 들도록....
            FG.Col = FG.MouseCol
            FG.Row = FG.MouseRow + 1
            FG.RowSel = FG.Rows - 1
            FG.ColSel = FG.MouseCol

            '
팝업 메뉴 표시함.
            PopupMenu mnuGridPopup
        End If
    End If
End Sub
 
 
"Insert Column" 메뉴를 선택하면 과목명을 입력받은 후 칼럼을 추가하고 양식을 유지시키기 위한 몇가지 작업을 추가로 처리한다. 핵심 코드는 굵게 표시한 2줄이다. 칼럼수를 늘린 후에 ColPosition 속성을 이용해서 추가된 칼럼(.Cols-1)을 사용자가 선택한 칼럼(.Col) 앞으로 이동시키는 것이다. 아주 간편하게 처리된다.
 
Private Sub mnuInsertColumn_Click()
    With FG
        ' insert column
        Dim str As String
        str = InputBox("
과목명을 입력하세요")
        If str <> "" Then
            .Cols = .Cols + 1          ' add column
            .ColPosition(.Cols - 1) = .Col    ' move into place

            .Cell(flexcpText, 1, .Col) = str
            .Cell(flexcpAlignment, 1, .Col) = flexAlignCenterCenter
            .Cell(flexcpText, 0, .Col) = "
과목"
        End If
    End With
End Sub
 
사용자 삽입 이미지
 
 
 
"Remove Column" 메뉴를 선택하면 사용자가 선택한 칼럼(.Col)을 마지막 칼럼(.Cols-1)으로 이동시킨 후에 칼럼의 수를 1만큼 감소시켜 삭제하는 효과를 준다. 어려울게 없다.
 
Private Sub mnuRemoveColumn_Click()
    With FG
        ' delete column
        .ColPosition(.Col) = .Cols - 1 ' move to right
        .Cols = .Cols - 1              ' delete column

        '
칼럼이 삭제됐으므로 계산을 다시 수행한다.
        Dim nTotal As Integer
        Dim dAverage As Single

        For i = 2 To .Rows - 1
            nTotal = .Aggregate(flexSTSum, i, 2, i, .Cols - 3)
            dAverage = .Aggregate(flexSTAverage, i, 2, i, .Cols - 3)

            .Cell(flexcpText, i, .Cols - 2) = CStr(nTotal)
            .Cell(flexcpText, i, .Cols - 1) = Format(dAverage, "#,##.0")
        Next
    End With
End Sub
 
 
지금까지 FlexGrid가 제공하는 기능 중 내가 주로 쓸 몇가지 기능 위주로 알아봤다. 매뉴얼을 살펴보니 이것 외에도 다양한 기능을 제공하는데, 그럼에도 불구하고 300달러의 가격 밖에 안되니 가격대 성능비가 뛰어난 제품이라 하겠다. 아주 마음에 든다.
 
 
REFERENCE
 
[1] VSFlexGrid 8.0 Manual, ComponentOne, 2005.
     - f:\ftp_root\program\develop\FlexGrid\VSFlexGrid8Manual2005.pdf
     - pp.269, FAQ: How can I add or delete a column at a given position?
[2] Francesco Balena, "Programming Microsoft Visual Basic 6.0", Microsoft Press, 1999.
     - Chapter 3. Intrinsic Controls, Menus.
 
Project Folder : D:\KDSONG\Study\Visual Basic\Controls\VSFlexGrid\FlexGridInsertRemove\
 
KEYWORDS : FlexGrid grid selection insert remove column copy paste 리드 복사 붙여넣기 선택 영역
열 칼럼 삽입 삭제
posted by 권오성의 Biomedical Engineering 2007. 8. 22. 13:46
아래와 같은 메시지가 나올 경우 소스에 다음과 같이 델이게이트 처리를 해주시면 해결됩니다.

사용자 삽입 이미지



//Delegate로 처리하는 부분
this.Invoke(new MethodInvoker(delegate()
{
*** 어쩌구 저쩌구 데이터를 뿌려주는 메소드 안의 내용.
}));

이렇게 하시면 위의 에러는 해결됩니다.
posted by 써니루루 2007. 7. 20. 17:21

.net Window form에서 컨트롤을 드래그 드롭하는 예제를 보면서 DragEnter와 DragDrop이벤트를 발췌해서 소개한다.


  /// <summary>
  /// The DragEnter event of the target control fires when the mouse enters
  /// a target control during a drag operation, and is used to determine if a drop
  /// will be allowed over this control.  This generally involves checking the type
  /// of data being dragged, the type of effects allowed (copy, move, etc.),
  /// and potentially the type and/or the specific instance of the source control that
  /// initiated the drag operation.
  ///
  /// This event will fire only if the AllowDrop property of the target control has
  /// been set to true.
  /// </summary>
  /// <param name="sender">The source of the event.</param>
  /// <param name="e">A DragEventArgs that contains the event data.</param>
  private void listBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
  {
   // Display some information about the DragDrop information in the
   // richTextBox1 control to show some of the information available.
   richTextBox1.Text = "Source Control: " + sourceControl.Name +
    "\r\nSource Control Type: " + sourceControl.GetType().Name +
    "\r\nAllowed Effect: " + e.AllowedEffect +
    "\r\nMouse Button: " + mouseButton.ToString() + "\r\n" +
    "\r\nAvailable Formats:\r\n";

   // Data may be available in more than one format, so loop through
   // all available formats and display them in richTextBox1.
   foreach (string availableFormat in e.Data.GetFormats(true))
   {
    richTextBox1.Text += "\t" + availableFormat + "\r\n";
   }

   // This control will use any dropped data to add items to the listbox.
   // Therefore, only data in a text format will be allowed.  Setting the
   // autoConvert parameter to true specifies that any data that can be
   // converted to a text format is also acceptable.
   if (e.Data.GetDataPresent(DataFormats.Text, true))
   {
    // Some controls in this sample allow both Copy and Move effects.
    // If a Move effect is allowed, this implementation assumes a Move
    // effect unless the CTRL key was pressed, in which case a Copy
    // effect is assumed.  This follows standard DragDrop conventions.
    if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move && (e.KeyState & ctrlKey) != ctrlKey)
    {
     // Show the standard Move icon.
     e.Effect = DragDropEffects.Move;
    }
    else
    {
     // Show the standard Copy icon.
     e.Effect = DragDropEffects.Copy;
    }
   }
  }

  /// <summary>
  /// The DragDrop event of the target control fires when a drop actually occurs over
  /// the target control.  This is where the data being dragged is actually processed.
  ///
  /// This event will fire only if the AllowDrop property of the target control has
  /// been set to true.
  /// </summary>
  /// <param name="sender">The source of the event.</param>
  /// <param name="e">A DragEventArgs that contains the event data.</param>
  private void listBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
  {

   // Store the data as a string so that it can be accessed from the
   // mnuCopy and mnuMove click events.
   sourceData = e.Data.GetData(DataFormats.Text, true).ToString();

   // If the right mouse button was used, provide a context menu to allow
   // the user to select a DragDrop effect.  The mouseButton is recorded in the
   // MouseDown event of the source control.
   if (mouseButton == MouseButtons.Right)
   {
    // Show a context menu, asking which operation to perform.
    // The ProcessData() call is then made in the click event
    // of the mnuCopy and mnuMove menu items.  Show only those
    // menu items that correspond to an allowed effect.
    mnuCopy.Visible = ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy);
    mnuMove.Visible = ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move);
    contextMenu1.Show(listBox1, new Point(20,20));
   }
   else
   {
    // Set the deleteSource member field based on the Effect.
    // The Effect is preset in the DragEnter event handler.
    deleteSource = (e.Effect == DragDropEffects.Move);

    // The processing of the data is done in a separate call, since
    // this is also called from the click event of the contextMenu1 items.
    ProcessData();

   }
  }

posted by 써니루루 2007. 7. 19. 02:38
간단히 .NET 2.0 C# Windows form 으로 개발한 적금 계산하는 프로그램입니다.

적금이 얼마나 될지 궁금한 일이 많은데 가끔씩 한번 찾아보게 되서 동료가 만든 프로그램을 올려봅니다.

짧은 시간에 짠거라 많은 기능은 기대하지 말아주세용;