Add a New Event to a Component: Right-Click in a TDBGrid

Add a New Event to a Component: Right-Click in a TDBGrid

Question:
I need to add a right-click event to aTDBGrid, but am ata loss as to how to accomplish it. I want to pop up a menu. Do you knowhow?

Answer:
Before I startinto this, there is an easier way to handle a right-mouse click topop up a menu of sorts: Drop a TPopupMenu on a form and set its AutoPopupto True, then set the DBGrid’s PopupMenu property to the name of theTPopupMenu.

It’s amazing how easy it is (at least in manycases) to add functionality to a component. Mouse clicks are problablythe easiest to implement, because the message structure of the windows messageis fairly simple — it’s only one parameter!

unit Extgrid;interfaceuses  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,  Forms, Dialogs, Grids, DBGrids;type  TExtDBGrid = class(TDBGrid)  private    { Private declarations }    FOnRightClick : TNotifyEvent;    procedure WMRButtonDown(var Message : TWMRButtonDown); messageWM_RBUTTONDOWN;  protected    { Protected declarations }  public    { Public declarations }  published    { Published declarations }    property OnRightClick: TNotifyEvent read FOnRightClick write FOnRightClick;  end;procedure Register;implementationprocedure TExtDBGrid.WMRButtonDown(var Message : TWMRButtonDown);begin  inherited;  if Assigned(FOnRightClick) then    FOnRightClick(Self);end;procedure Register;begin  RegisterComponents('Samples', [TExtDBGrid]);end;end.

Okay, what did we just do? First of all we defined an eventhandling procedure:

procedure WMRButtonDown(var Message : TWMRButtonDown); messageWM_RBUTTONDOWN;

the message directive following the declaration tellsthe component to watch for the message WM_RBUTTONDOWN, which is the messagefor the right mouse button down. What we’ve done with this procedure ismake the component look for this message. However, mere awareness isn’tenough, by far! We have to add a property of type TNotifyEvent (whichif you remember is the domain in which mouse clicks fall) so that userscan add code to process it. So, in the published section of theunit, we added:

property OnRightClick: TNotifyEvent read FOnRightClick writeFOnRightClick;

to assign the message to the component.

If you’re familiar with writing components, you’ll notice the differencein how message properties are handled as opposed to regular properties.Typically, when setting and getting property values you would use a Getor Set method or a direct read and write to the properties’ fields. Inessence, things happen in response to the change in state of the property.This appears to occur in the notation of the unit above, but there’s actuallya bit more going on. In fact, it’s a bit backwards. The FOnRightClickis not really a variable, but rather a pointer to an event-handlingprocedure. Luckily we don’t have to know the mechanics behind this, becausethe compiler will automatically do all the work for us in creating thehandler’s declaration. However, if we look at the WMRButtonDownprocedure, we’ll see that the variable is actually being used as a procedurecall:

procedure TExtDBGrid.WMRButtonDown(var Message : TWMRButtonDown);begin  inherited;  if Assigned(FOnRightClick) then    FOnRightClick(Self);end;

As I mentioned above, message handling works sort of in reverseof regular property setting. Where with a regular property, the changein the state of the property causes some code to fire off with an event,it’s a message-aware procedure that sits in memory that changes the stateof the message property. To illustrate this, in the code example above,the WMRButtonDown procedure makes the component aware of the right-click.Whenever the message appears in the message queue, WMRButtonDown fires.When it fires, it in turn fires off the FOnRightClick procedure, whichon the component would be the event handler OnRightClick.

Use this code as a basis for writing your own events. Theonline help under WinAPI help has excellent discussions of messages andhow they interact with the system. In addition to this though, I stronglyrecommend getting a book on the Windows API and getting the Resource Kitand SDK to really get into event handling.

devx-admin

devx-admin

Share the Post:
Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by

What You Need to Know About Cloud Security Strategies

What You Need to Know About Cloud Security Strategies

Today, many businesses are adopting cloud computing services. As a result, it’s important to recognize that security measures for data in the cloud are different from those in traditional on-premises

Romanian Energy Security

Eastern Europe is Achieving Energy Security

Canada and Romania have solidified their commitment to energy security and independence from Russian energy exports by signing a $3-billion export development agreement. The deal is centered on constructing two

Seamless Integration

Unlocking Seamless Smart Home Integration

The vision of an intelligently organized and interconnected smart home that conserves time, energy, and resources has long been desired by many homeowners. However, this aspiration has often been hindered

New Algorithm

MicroAlgo’s Groundbreaking Algorithm

MicroAlgo Inc. has revealed the creation of a knowledge-augmented backtracking search algorithm, developed through extensive research in evolutionary computational techniques. The algorithm is designed to boost problem-solving effectiveness, precision, and

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses