Docsity

Aprenda Visual C#, Manuais, Projetos, Pesquisas de Informática

Pré-visualização parcial do texto

Baixe Aprenda Visual C# e outras Manuais, Projetos, Pesquisas em PDF para Informática, somente na Docsity!

Aprenda Visual

C# 2008 em

24 Horas -

Kit Completo

do Iniciante

Índice

PART I - The Visual C#

2008 Environment

HORA 1 Jumping In with Both Feet: A Visual C# 2008 Programming Tour 7

HORA 2 Navigating Visual C# 2008 31

HORA 3 Understanding Objects and Collections 59

HORA 4 Understanding Events 81

será útil em muitas aplicações do mundo real que você criará, mas a meta deste

capítulo é para você perceber apenas quanta diversão é programar com o Visual

C#. In this hour, you’ll complete a quick tour that takes you step by step through creating a complete, albeit

small, Visual C# program. Most introductory programming books start out with the reader creating a simple Hello World program. I’ve yet to see a Hello World program that’s the least bit helpful (they usually do nothing more than print hello world to the screen—oh, what fun). So, instead, you’ll create a picture viewer application that lets you view Windows bitmaps and icons on your computer. You’ll learn how to let a user browse for a file and how to display a selected picture file on the screen. The techniques you learn in this chapter will come in handy in many real-world applications that you’ll create, but the goal of this chapter is for you to realize just how much fun it is to program with Visual C#.

Começando com o Visual C# 2008

Antes de você começar a criar programas no Visual C# 2008, você deve estar

familiarizado com as seguintes condições: Before you begin creating programs in Visual C# 2008,

you should be familiar with the following terms:

. Componente distribuível - A versão de um projeto final, compilada. Os

componentes podem ser distribuídos para outras pessoas e outros

computadores, e eles não requerem o ambiente de desenvolvimento do Visual

C# 2008 (as ferramentas você usa para criar um programa .NET) para

executar (embora eles requeiram o runtime .NET que eu discuto na Hora 23,

"Desenvolvendo Aplicações"). Os componentes distribuíveis são

freqüentemente chamados de componentes. Na Hora 23, você aprenderá a

distribuir o programa Picture Viewer que você está a ponto de construir para

outros computadores. Distributable component —The final, compiled version of a project.

Components can be distributed to other people and other computers, and they don’t require the Visual C# 2008 development environment (the tools you use to create a .NET program) to run (although they do require the .NET runtime, which I discuss in Hour 23, “Deploying Applications”). Distributable components are often called

programs. In Hour 23, you’ll learn how to distribute the Picture Viewer program that you’re about to build to

other computers.

. Projeto - Uma coleção de arquivos que pode ser compilados para criar um

componente distribuível (programa). Existem muitos tipos de projetos e

aplicações complexas podem consistir de múltiplos projetos, como um projeto

de aplicação Windows e suporte a projetos de biblioteca de ligação dinâmica

(DLL). Project —A collection of files that can be compiled to create a distributable component (program).

There are many types of projects, and complex applications might consist of multiple projects, such as a Windows application project, and support dynamic link library (DLL) projects.

. Solução - uma coleção de projetos e arquivos que compõem uma aplicação ou

componente. Solution —A collection of projects and files that make up an

application or component.

A propósito: O Visual C# é parte de uma entidade maior conhecida como .NET Framework. O .NET Framework abarca toda a tecnologia .NET, incluindo o Visual Studio .NET (a suite de ferramentas de desenvolvimento) e a Linguagem Comum Runtime (CLR) que é o conjunto de arquivos que compõem o núcleo de tudas as aplicações .NET. Você aprenderá sobre estes ítens em mais detalhe a medida que você progridir por este livro. Por agora, perceba que o Visual C# é uma das muitas linguagems que existe dentro da família .NET. Muitas outras linguagems, como o Visual Basic, também é uma linguagem .NET, que faz uso do CLR, e é desenvolvida dentro do Visual Studio .NET. By the Way Visual C# is part of a larger entity known as the .NET Framework. The .NET Framework encompasses all the .NET technology, including Visual Studio .NET (the suite of development tools) and

the Common Language Runtime (CLR), which is the set of files that make up the core of all .NET applications. You’ll learn about these items in more detail as you progress through this book. For now, realize that Visual C# is one of many languages that exist within the .NET family. Many other languages, such as Visual Basic, are also .NET languages, make use of the CLR, and are developed within Visual Studio .NET.

O Visual Studio 2008 é um ambiente de desenvolvimento completo, e ele é

chamado de IDE (abreviatura de Integrated Development Dnvironment, ambiente

de desenvolvimento integrado). A IDE é o framework de design no qual você

constrói as aplicações; toda ferramenta que você precisará criar seus projetos do

Visual C# são acessados de dentro da IDE do Visual C#. Novamente, o Visual

Studio 2008 suporta o desenvolvimento de muitas diferentes linguagens - sendo o

Visual C# uma das mais populares. O próprio ambiente não é o Visual C#, mas a

linguagem que você usa dentro do Visual Studio 2008 é o Visual C#. Para trabalhar

com os projetos do Visual C#, você inicia primeiro a IDE do Visual Studio 2008.

Visual Studio 2008 is a complete development environment, and it’s called the IDE (short for integrated development environment ). The IDE is the design framework in which you build applications; every tool you’ll need to create your Visual C# projects is accessed from within the Visual C# IDE. Again, Visual Studio 2008 supports development in many different languages—Visual C# being one of the most popular. The environment itself is not Visual C#, but the language you use within Visual Studio 2008 is Visual C#. To work with Visual C# projects, you first start the Visual Studio 2008 IDE.

Inicie agora o Visual Studio 2008 escolhendo Microsoft Visual C# 2008 Express

Edition em seu menú Start/Programs. Se você está rodando a versão de completa

do .NET, seu atalho pode ter um nome diferente. Neste caso, localize o atalho em

seu menú Start e clique para iniciar a IDE do Visual Studio .NET uma vez. Start

Visual Studio 2008 now by choosing Microsoft Visual C# 2008 Express Edition on your Start/Programs menu. If you are running the full retail version of .NET, your shortcut may have a different name. In this case, locate the shortcut on your Start menu and click it once to start the Visual Studio .NET IDE.

Criando um Novo Projeto

Quando primeiro você inicia Visual Studio. .NET, você é apresentado a aba Start

Page dentro da IDE. Você pode abrir projetos previamente criados ou pode criar

novos projetos da página Start (veja a Figura 1.1). Por esta excursão rápida, você

vai criar uma nova aplicação Windows, assim abra o menú File e clique em New

Project para mostrar o dialog box New Project mostrado na Figura 1.2. When you first

start Visual Studio .NET, you’re shown the Start Page tab within the IDE. You can open projects created previously or create new projects from this Start page (see Figure 1.1). For this quick tour, you’re going to create a new Windows application, so open the File menu and click New Project to display the New Project dialog box shown in Figure 1.2.

A propósito: Se sua página Start não se parecer com a da Figura 1.1, chances são

de que você mudou as configurações padrões. Na Hora 2, "Navegando no Visual C#

2008", eu lhe mostrarei como as alterar. By the Way If your Start page doesn’t look like the one

in Figure 1.1, chances are that you’ve changed the default settings. In Hour 2, “Navigating Visual C# 2008,” I’ll show you how to change them back.

muito esquisitamente, você especifica o nome do projeto que você está

criando. Entre com Picture Viewer no text box Name. At the bottom of the New Project

dialog box is a Name text box. This is where, oddly enough, you specify the name of the project you’re creating. Enter Picture Viewer in the Name text box.

3 Clique no OK para criar o projeto. Click OK to create the project.

Você Sabia? Sempre configure o text box Name para algo significante antes de criar

um projeto, ou você terá mais trabalho para fazer isto depois se você quiser mover

ou renomear o projeto. Did you Know? Always set the Name text box to something meaningful before

creating a project, or you’ll have more work to do later if you want to move or rename the project.

Quando o Visual C# criar um novo projeto de aplicação Windows, adicione um form

(a janela cinza vazia) para você iniciar a construção da interface - as janelas

gráficas com que você interagirá - para sua aplicação (veja a Figura 1.3). When

Visual C# creates a new Windows application project, it adds one form (the empty gray window) for you to begin building the interface —the graphical windows with which you interact—for your application (see Figure 1.3).

A propósito: Dentro do Visual Studio 2008, o form é o termo dado à visão em

tempo de design da janelas que pode ser exibida a um usuário. By the Way Within

Visual Studio 2008, form is the term given to the design-time view of windows that can be displayed to a user.

FIGURE 1.3 - New Windows applications start with a blank form; the fun is just

beginning!

Seu ambiente do Visual Studio 2008 pode parecer diferente do mostrado nas

figuras desta hora por causa da edição do Visual Studio 2008 que você está

usando, se você já brincou com o Visual Studio 2008, e outros fatores como a

resolução do seu monitor. Entretanto, todos os elementos discutidos por esta hora

existem em todas as edições do Visual Studio 2008. (Se uma janela mostrada em

uma figura não for exibida em sua IDE, use o menú View para mostrá-la). Your

Visual Studio 2008 environment might look different from that shown in the figures of this hour because of the edition of Visual Studio 2008 you’re using, whether you’ve already played with Visual Studio 2008, and other factors such as the resolution of your monitor. All the elements discussed in this hour exist in all editions of Visual Studio 2008, however. (If a window shown in a figure isn’t displayed in your IDE, use the View menu to display it.)

A propósito: para criar um programa que pode ser rodado em outro computador,

você inicia então criando um projeto e compilando o projeto em um componente

como um executável (programa que um usuário pode executar) ou uma DLL (um

componente que pode ser usado por outros programas e componentes). O processo

de compilação é discutido em detalhes na Hora 23, "Desenvolvendo Aplicações." O

importante a notar neste momento é que, quando você ouvir alguém se referir a

criação ou escrita de um programa, da mesma maneira que você está agora

criando o programa Picture Viewer, eles estão se referindo à conclusão de todos os

passos até aquí e incluindo a compilação do projeto para um arquivo distribuível.

By the Way To create a program that can be run on another computer, you start by creating a project and then compiling the project into a component such as an executable (program a user can run) or a DLL (a component that can be used by other programs and components). The compilation process is discussed in detail in Hour 23, “Deploying Applications.” The important thing to note at this time is that when you hear someone refer to creating or writing a program, just as you’re creating the Picture Viewer program now, they’re referring to the completion of all steps up to and including compiling the project to a distributable file.

Entendendo o Ambiente do Visual Studio .NET

A primeira vez que você rodar o Visual Studio 2008, você notará que a IDE contém

várias janelas, como à janela da direita do Solution Explorer que é usada para ver

os arquivos que compõem um projeto. Além destas janelas, a IDE contém várias

abas, como a aba vertical da Toolbox na extremidade à esquerda da IDE (refere-se

a Figura 1.3). Tente isto agora: Clique na aba Toolbox para mostrar a janela

Toolbox (clicando em uma aba exibe uma janela associada). Você pode pairar o

mouse sobre uma aba durante alguns segundos para também mostrar a janela.

Para esconder a janela, simplesmente mova o mouse para fora da janela (se você

pairar por sobre a aba para mostrá-la) ou dar um clique em outra janela. Para

fechar completamente a janela, clique no botão Close (X) na barra de título da

janela. The first time you run Visual Studio 2008, you’ll notice that the IDE contains a number of windows, such

as the Solutions Explorer window on the right, which is used to view the files that make up a project. In addition to these windows, the IDE contains a number of tabs, such as the vertical Toolbox tab on the left edge of the IDE (refer to Figure 1.3). Try this now: Click the Toolbox tab to display the Toolbox window (clicking a tab displays an associated window). You can hover the mouse over a tab for a few seconds to display the window as well. To hide the window, simply move the mouse off the window (if you hovered over the tab to display it) or click on another window. To close the window completely, click the Close (X) button in the window’s title bar.

A propósito: Se você abrir a toolbox clicando em sua aba em lugar de pairar por

sobre a aba, a toolbox não fecha automaticamente. Ao invés disso, ela fica aberto

até que você dê um clique em outra janela. By the Way If you opened the toolbox by clicking its

tab rather than hovering over the tab, the toolbox does not automatically close. Instead, it stays open until you click on another window.

Você pode ajustar o tamanho e a posição de qualquer uma destas janelas, e você

pode até mesmo esconder e pode mostrar para eles quando necessário. Você

aprenderá a personalizar seu ambiente de design na Hora 2. You can adjust the size and

position of any of these windows, and you can even hide and show them as needed. You’ll learn how to customize your design environment in Hour 2.

Tome Cuidado! A menos que, especificamente instruído para fazer assim, não

clique duas vezes em nada no ambiente de design do Visual Studio 2008. Clicando

duas vezes na maioria dos objetos produz um resultado completamente diferente

do que com um único clique. Se você clicar duas vezes em um objeto erradamente

em um form (discutido brevemente), uma janela de código será exibida. Ao parte

superior da janela de código é um conjunto de abas: uma para o design do form e

uma para o código. Clique na aba para o design do form esconder a janela de

código e voltar ao form. Watch Out! Unless specifically instructed to do so, don’t double-click anything in the Visual Studio 2008 design environment. Double-clicking most objects produces an entirely different result than single-clicking does. If you mistakenly double-click an object on a form (discussed shortly), a code window is displayed. At the top of the code window is a set of tabs: one for the form design and one for the code. Click the tab for the form design to hide the code window and return to the form.