Читаем Виртуальная библиотека Delphi полностью

Как показывать нестандартный встроенный редактор (inplace editor) в ячейке stringgrid (например combobox).

Ответ:

См. пример

Пример:

procedure TForm1.FormCreate(Sender: TObject);

begin

 {Высоту combobox'а не изменишь, так что вместо combobox'а будем изменять высоту строки grid'а !}

 StringGrid1.DefaultRowHeight := ComboBox1.Height;

 {Спрятать combobox}

 ComboBox1.Visible := False;

 ComboBox1.Items.Add('Delphi Kingdom');

 ComboBox1.Items.Add('Королевство Дельфи');

end;


procedure TForm1.ComboBox1Change(Sender: TObject);

begin

 {Перебросим выбранное в значение из ComboBox в grid}

 StringGrid1.Cells[StringGrid1.Col, StringGrid1.Row] :=ComboBox1.Items[ComboBox1.ItemIndex];

 ComboBox1.Visible := False;

 StringGrid1.SetFocus;

end;


procedure TForm1.ComboBox1Exit(Sender: TObject);

begin

 {Перебросим выбранное в значение из ComboBox в grid}

 StringGrid1.Cells[StringGrid1.Col, StringGrid1.Row] :=ComboBox1.Items[ComboBox1.ItemIndex];

 ComboBox1.Visible := False;

 StringGrid1.SetFocus;

end;


procedure TForm1.StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);

var R: TRect;

begin

 if ((ACol = 3) AND (ARow <> 0)) then begin

  {Ширина и положение ComboBox должно соответствовать ячейке StringGrid}

  R := StringGrid1.CellRect(ACol, ARow);

  R.Left := R.Left + StringGrid1.Left;

  R.Right := R.Right + StringGrid1.Left;

  R.Top := R.Top + StringGrid1.Top;

  R.Bottom := R.Bottom + StringGrid1.Top;

  ComboBox1.Left := R.Left + 1;

  ComboBox1.Top := R.Top + 1;

  ComboBox1.Width := (R.Right + 1) - R.Left;

  ComboBox1.Height := (R.Bottom + 1) - R.Top;

  {Покажем combobox}

  ComboBox1.Visible := True;

  ComboBox1.SetFocus;

 end;

 CanSelect := True;

end;


Вопрос:

Как узнать есть ли в заданном CD-ROM'е Audio CD?

Ответ:

Можно использовать функцию Windows API GetDriveType() чтобы определить является ли дисковод CD-ROM'мом. И функцию API GetVolumeInformation() чтобы проверить VolumeName на равенство 'Audio CD'.

Пример:

function IsAudioCD(Drive : char) : bool;

var

 DrivePath : string;

 MaximumComponentLength : DWORD;

 FileSystemFlags : DWORD;

 VolumeName : string;

Begin

 result := false;

 DrivePath := Drive + ':\';

 if GetDriveType(PChar(DrivePath)) <> DRIVE_CDROM then exit;

 SetLength(VolumeName, 64);

 GetVolumeInformation(PChar(DrivePath),PChar(VolumeName), Length(VolumeName),nil,MaximumComponentLength,FileSystemFlags,nil,0);

 if lStrCmp(PChar(VolumeName),'Audio CD') = 0 then result := true;

end;


function PlayAudioCD(Drive : char) : bool;

var mp : TMediaPlayer;

begin

 result := false;

 Application.ProcessMessages;

 if not IsAudioCD(Drive) then exit;

 mp := TMediaPlayer.Create(nil);

 mp.Visible := false;

 mp.Parent := Application.MainForm;

 mp.Shareable := true;

 mp.DeviceType := dtCDAudio;

 mp.FileName := Drive + ':';

 mp.Shareable := true;

 mp.Open;

 Application.ProcessMessages;

 mp.Play;

Перейти на страницу:

Похожие книги

Programming with POSIX® Threads
Programming with POSIX® Threads

With this practical book, you will attain a solid understanding of threads and will discover how to put this powerful mode of programming to work in real-world applications. The primary advantage of threaded programming is that it enables your applications to accomplish more than one task at the same time by using the number-crunching power of multiprocessor parallelism and by automatically exploiting I/O concurrency in your code, even on a single processor machine. The result: applications that are faster, more responsive to users, and often easier to maintain. Threaded programming is particularly well suited to network programming where it helps alleviate the bottleneck of slow network I/O. This book offers an in-depth description of the IEEE operating system interface standard, POSIX (Portable Operating System Interface) threads, commonly called Pthreads. Written for experienced C programmers, but assuming no previous knowledge of threads, the book explains basic concepts such as asynchronous programming, the lifecycle of a thread, and synchronization. You then move to more advanced topics such as attributes objects, thread-specific data, and realtime scheduling. An entire chapter is devoted to "real code," with a look at barriers, read/write locks, the work queue manager, and how to utilize existing libraries. In addition, the book tackles one of the thorniest problems faced by thread programmers-debugging-with valuable suggestions on how to avoid code errors and performance problems from the outset. Numerous annotated examples are used to illustrate real-world concepts. A Pthreads mini-reference and a look at future standardization are also included.

David Butenhof

Программирование, программы, базы данных
Adobe InDesign CS3
Adobe InDesign CS3

Книга посвящена верстке и макетированию в программе Adobe InDesign CS3. Помимо того что в ней описываются возможности программы, рассматриваются также принципы и традиции верстки, приводятся примеры решения типичных задач. Все это позволит читателю не только овладеть богатым инструментарием программы, но и грамотно применять его.Материал книги разделен на логические части: теоретические сведения, инструментарий программы, решение задач, – а также рассчитан на два уровня подготовки читателей – начинающих и опытных пользователей, что выгодно отличает книгу от других изданий. Это позволит применять ее как новичкам для знакомства с программой, так и пользователям со стажем для пополнения своих знаний.

Владимир Гавриилович Завгородний , Владимир Завгородний

Программирование, программы, базы данных / Программное обеспечение / Книги по IT
1001 совет по обустройству компьютера
1001 совет по обустройству компьютера

В книге собраны и обобщены советы по решению различных проблем, которые рано или поздно возникают при эксплуатации как экономичных нетбуков, так и современных настольных моделей. Все приведенные рецепты опробованы на практике и разбиты по темам: аппаратные средства персональных компьютеров, компьютерные сети и подключение к Интернету, установка, настройка и ремонт ОС Windows, работа в Интернете, защита от вирусов. Рассмотрены не только готовые решения внезапно возникающих проблем, но и ответы на многие вопросы, которые возникают еще до покупки компьютера. Приведен необходимый минимум технических сведений, позволяющий принять осознанное решение.Компакт-диск прилагается только к печатному изданию книги.

Юрий Всеволодович Ревич

Программирование, программы, базы данных / Интернет / Компьютерное «железо» / ОС и Сети / Программное обеспечение / Книги по IT