The Slider Control


Overview

A slider is a Windows control equipped with a small bar, also called a thumb, that slides along a visible line. There are two types of sliders: horizontal and vertical:

To use the slider control, the user can drag the thumb in one of two directions. If the slider is horizontal, the user can drag the thumb left or right. The thumb of a vertical slider can be dragged up or down. This changes the position of the thumb. The user can also click the desired position along the line to place the thumb at the desired location. Alternatively, when the slider has focus, the user can also use the arrow keys of the keyboard to move the thumb.

A slider is configured with a set of values from a minimum to a maximum. Therefore, the user can make a selection included in that range. Optionally, a slider can be equipped with small indicators called ticks:

The ticks can visually guide the user for the available positions of the thumb mark. A slider can be used to let the user specify a value that conforms to a range. When equipped with ticks, a slider can be used to control exact values that the user can select in a range, preventing the user from setting just any desired value.

  1. For this application, we will help the user display different pictures from a series of 10. If you want, you can start a new Dialog-based application named CarInventory with no About Box and set the Dialog Title to Car Inventory
    Delete the TODO line and the OK button

  2. Save the following pictures to your hard drive:
     

  3. On the main menu, click Insert -> Resource or Project -> Add Resource…

  4. On the Add Resource dialog box, click Import… and import the above pictures. If you are using MSVC 6, you may receive a message box when you import each picture, simply click OK

  5. Change the ID of the new bitmap to IDB_CIVIC, IDB_ELANTRA, IDB_ESCAPE, IDB_ESCORT, IDB_FOCUS, IDB_MARQUIS, IDB_MYSTIQUE, IDB_NAVIGATOR, IDB_SENTRA, and IDB_SEPHIA respectively

  6. Add a Picture control to the top side of the dialog box and change its ID to IDC_PREVIEW

  7. Type to Bitmap and set its Bitmap to IDB_CIVIC

  8. Add a Control variable for the picture control and name it m_Preview

  9. To store the values for the controls on the dialog box, in the header file of the dialog box, declare a private UINT array named CarPicture[10]

  10. To initialize the array, type the following in the OnInitDialog event:
     

    BOOL CSlider1Dlg::OnInitDialog()
    {
    	CDialog::OnInitDialog();
    
    	SetIcon(m_hIcon, TRUE);			// Set big icon
    	SetIcon(m_hIcon, FALSE);		// Set small icon
    	
    	// TODO: Add extra initialization here
    	
    	CarPicture[0] = IDB_CIVIC;
    	CarPicture[1] = IDB_ELANTRA;
    	CarPicture[2] = IDB_ESCAPE;
    	CarPicture[3] = IDB_ESCORT;
    	CarPicture[4] = IDB_MARQUIS;
    	CarPicture[5] = IDB_MYSTIQUE;
    	CarPicture[6] = IDB_NAVIGATOR;
    	CarPicture[7] = IDB_SENTRA;
    	CarPicture[8] = IDB_FOCUS;
    	CarPicture[9] = IDB_SEPHIA;
    	
    	return TRUE;  // return TRUE  unless you set the focus to a control
    }
  11. To display default values in the dialog box, on top of its OnPaint() event, type the following:
     

    void CSlider1Dlg::OnPaint() 
    {
    	CBitmap Bmp;
    
    	Bmp.LoadBitmap(CarPicture[0]);
    
    	m_Preview.SetBitmap(Bmp);
    
    	UpdateData(FALSE);
    
    	if (IsIconic())
    	{
    		CPaintDC dc(this); // device context for painting
    
    		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
    
    		// Center icon in client rectangle
    		int cxIcon = GetSystemMetrics(SM_CXICON);
    		int cyIcon = GetSystemMetrics(SM_CYICON);
    		CRect rect;
    		GetClientRect(&rect);
    		int x = (rect.Width() - cxIcon + 1) / 2;
    		int y = (rect.Height() - cyIcon + 1) / 2;
    
    		// Draw the icon
    		dc.DrawIcon(x, y, m_hIcon);
    	}
    	else
    	{
    		CDialog::OnPaint();
    	}
    }
  12. Test the application and return to MSVC

Slider Creation

To provide a slider to an application, from the Controls toolbox, click the Slider button and click the desired area on the dialog box or the form.

To programmatically create a slider, declare a pointer to CSliderCtrl using the new operator. To initialize the control, call its Create() method. Here is an example:

BOOL CDlgSlide::OnInitDialog() 
{
	CDialog::OnInitDialog();

	// TODO: Add extra initialization here
	CSliderCtrl *TrackBar = new CSliderCtrl;

	TrackBar->Create(WS_CHILD | WS_VISIBLE,
	CRect(15, 20, 222, 50), this, 0x14);

	return TRUE; // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
  1. On the Controls toolbox, click the Slider button and click in lower-left section of the dialog box
  2. Save All

Slider Properties

After placing a slider control on a form or other host, by default, its assumes a horizontal direction. If you want a vertical slider, change the value of the Orientation property. If you are dynamically creating the control, its default orientation would be horizontal, whose style is TBS_HORZ. If you want a vertical slider, apply the TBS_VERT style:

BOOL CDlgSlide::OnInitDialog() 
{
CDialog::OnInitDialog();

	// TODO: Add extra initialization here
	CSliderCtrl *TrackBar = new CSliderCtrl;

	TrackBar->Create(WS_CHILD | WS_VISIBLE | TBS_VERT,
	CRect(20, 20, 50, 250), this, 0x14);

	return TRUE; // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

The new slider appears as one line, horizontal or vertical, that guides the user with the area to slide the thumb. When sliding the thumb along the line, the user can set only the value where the thumb is positioned. Alternatively, if you want the user to be able to select a range of values instead of just a value, at design time, you can set the Enable Selection property to True. This is equivalent to adding the TBS_ENABLESELECTION style. A slider equipped with this style displays a 3-D “whole” in the body of the slider:

The selection area allows the user to select a range of values.

The thumb of a slider can assume one of three shapes. By default, it appears as a rectangular box. Alternatively, you can convert one of its shorter borders to appear as an arrow. The shape of the thumb is controlled at design time by the Point property. Its default value is Both, which gives it a rectangular shape. You can get this same shape by omitting or adding the TBS_BOTH value.

For a horizontal slider, you can make the thumb’s arrow point to the left by changing the Point property to Top/Left. If the slider is horizontal, this Point value would orient the thumb arrow to the top:

To make the thumb of a dynamically created horizontal slider point up, add the TBS_TOP style. If the slider is vertical, to point its thumb to the left, add the TBS_LEFT style to it.

If you want the thumb to point down for a horizontal slider, set the Point property to Bottom/Right. This same value would make the thumb of a vertical slider point n the right direction:

To point the thumb up for a horizontal slider you are programmatically creating, add the TBS_BOTTOM. For the thumb of a vertical slider to point right, add the TBS_RIGHT to it.

If you want to guide the user with some ticks on the control, at design time, set the Tick Marks property to True. If you are dynamically creating the slider and you want it to display ticks, simply adding the either the TBS_VERT or the TBS_HORZ style equips the slider with ticks. If you don't want to display the ticks at all, at design time, clear the Tick Marks property or set its value to False.

The ticks are positioned on the side the thumb is pointing. If the slider is created with the Both value for the Point property or the TBS_BOTH style, the ticks would appear on both sides the thumb.

The thumb of a slider is used to scroll from one minimum value to another. The range of these extreme values can be divided in regular increments that can further guide the user with value selection. To display where these increments are set, at design time, set the Auto Ticks property to True or add the TBS_AUTOTICKS style to a dynamic slider.

  1. While the slider control is selected on the dialog box, on the Properties window, change its ID to IDC_SLIDER
  2. Check its Auto Ticks check box or set it to True
  3. Check its Tick Marks check box or set it to True
  4. Set its Point property to Top/Left
    Set to True the Tooltips property of the slider control (MSVC 7)
  5. Add a CSliderCtrl Control variable for the slider and name it m_CarSlider
  6. Save All

Slider Methods

As seen earlier, the slider control is based on the CSliderCtrl class. Therefore, we saw that we can dynamically create a slider by declaring pointer to CSliderCtrl and call its Create() method to initialize it. Once a slider has been designed and received the desired style, you can programmatically use it and provide the necessary feedback to the user.

A slider is a control that provides a range of values between which the user can navigate using the control’s thumb or by clicking on the slider’s line. Usually, the first aspect you may need to configure on your control is to specify its limit values. To specify the minimum value of a slider control, you can call the CSliderCtrl::SetRangeMin() method. Its syntax is:

void SetRangeMin(int nMin, BOOL bRedraw = FALSE);

The nMin value is the new minimum value that the slider can assume. The control is typically redrawn once the new value has been set. If you don't want the control to be redrawn, pass a second argument with the FALSE value. If the lowest value of the control has already been set and you want to find out what that value is, you can call the CSliderCtrl::GetRangeMin() method. Its syntax is:

int GetRangeMin() const;

This method simply returns the lowest value that the slider can assume when the user has dragged the thumb to the extreme left or bottom.

To set the highest value of a slider control, you can call the SliderCtrl::SetRangeMax() method. Its syntax is:

void SetRangeMax(int nMax, BOOL bRedraw = FALSE);

The nMax argument holds the new maximum value for the control. Here is an example:

BOOL CControlsDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();

	// TODO: Add extra initialization here
	m_Slider.SetRangeMin(0);
	m_Slider.SetRangeMax(50);

	return TRUE; // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

If the maximum value of the control had previously been set, you can find it out by calling the SliderCtrl::GetRangeMax() method. Its syntax is:

int GetRangeMax() const;

This method returns the highest value that the slider control can have.

To set both the minimum and the maximum values of the slider with one line of code, you can call the CSliderCtrl::SetRange() method. Its syntax is:

void SetRange(int nMin, int nMax, BOOL bRedraw = FALSE);

The nMin and the nMax arguments hold the lowest and the highest respective values of the control. Here is an example:

BOOL CControlsDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();

	// TODO: Add extra initialization here
	m_Slider.SetRange(0, 50);

	return TRUE; // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

If the control is already functioning and you want to know its limit values, you can call the CSliderCtrl::SetRange() method whose syntax is:

void GetRange(int& nMin, int& nMax) const;

This method returns two values, namely the lowest value, as nMin, and the highest value, as nMax.

Once the minimum and maximum values have been set, the user can slide the thumb to select a value or a range. This value is what mostly interests you. While sliding the thumb, the value of the slider is called its position. At startup or at any time, you can set a specific position for the thumb. This can be done by calling the CSliderCtrl::SetPos() method. Its syntax is:

void SetPos(int nPos);

The nPos argument holds the new position of the slider. Here is an example:

BOOL CControlsDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();

	// TODO: Add extra initialization here
	m_Slider.SetRange(0, 50);
	m_Slider.SetPos(32);

	return TRUE; // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

The value specified using the SetPos() method should be in the range nMax – nMin of the SetRange() method. If there is a possibility that this value is outside the valid range, you can call the CSliderCtrl::VerifyPos() method to check it. Its syntax is:

void VerifyPos( );

When the position of the thumb has change and you want to find out what it is, call the CSliderCtrl::GetPos() method whose syntax is:

int GetPos() const;

If the slider control was specified to let the user select a range, you can define your own selected range at any time by callin the CSliderCtrl::SetSelection() method. Its syntax is:
void SetSelection(int nMin, int nMax);

When calling this method, make sure you specify the nMin and the nMax values so that this nMin is greater than the minimum value of the slider and this nMax is less than the highest possible value of the slider. Furthermore, the value of this nMin must be less than that of nMax. This relationshipd can be illustrated as follows:

Minimum <= nMin < nMax <= Maximum

Here is an example:

BOOL CControlsDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();

	// TODO: Add extra initialization here
	m_Slider.SetRange(0, 50);
	m_Slider.SetPos(32);
	m_Slider.SetSelection(22, 42);

	return TRUE; // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

If a selected range has been performed on the slider, if you want to get the minimum and the maximum values of the selection, you can call the CSliderCtrl::GetSelection() method whose syntax is:
void GetSelection(int& nMin, int& nMax) const;

This method returns two values, the minimum as nMin and the maximum as nMax.

If the slider controla is configure to displays ticks, you can specify their frequncy with a call to the CSliderCtrl::SetTicFreq() method. Its syntax is:

void SetTicFreq(int nFreq);
  1. In the OnInitDialog event of the dialog class, set the range of values of the slider to 0 to 9 and the frequency of its ticks to:
     
    	m_CarSlider.SetRange(1, 10);
    	m_CarSlider.SetTicFreq(1);
    
    	return TRUE; // return TRUE unless you set the focus to a control
    }
  2. Test the application and return to MSVC

Slider Events

On its own, the slider controls can send three notification messages:

  • The NM_OUTOFMEMORY message is sent when the slider has run out of memory and could not complete a task

  • The NM_RELEASECAPTURE message is sent when the user releases the mouse on the slider

  • The NM_CUSTOMDRAW message is used if you want to draw something on the slider or you want to customize the appearance of the slider beyond what Visual C++ proposes

For its functionality, the slider highly relies on its parent. When the user clicks the thumb or any part of the slider, which causes it to slide, a scroll event is fired. If the slider is horizontal, the CWnd::OnHScroll() event is sent. If the slider is vertical, the CWnd::OnVScroll() event is sent.

  1. Change the OnPaint() event of the dialog class as follows:
     

    void CCarInventoryDlg::OnPaint() 
    {
    	int CurPos = m_CarSlider.GetPos() - 1;
    	CBitmap Bmp;
    
    	Bmp.LoadBitmap(CarPicture[CurPos]);
    
    	m_Picture.SetBitmap(Bmp);
    	UpdateData(FALSE);
    
    	. . .
    }
  2. Using either the ClassWizard (MSVC 6) or the Messages button , for the dialog, generate the WM_HSCROLL message and implement it as follows:
     

    vvoid CCarInventoryDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) 
    {
    	// TODO: Add your message handler code here and/or call default
    	CRect RectPicture;
    
    	// Get the location and dimensions of the picture area
    	m_Preview.GetWindowRect(&RectPicture);
    
    	// Convert the current coordinates from the monitor (Screen) to the dialog box (Client)
    	ScreenToClient(&RectPicture);
    	// Repaint the picture area
    	InvalidateRect(&RectPicture);
    
    	CDialog::OnHScroll(nSBCode, nPos, pScrollBar);
    }
  3. Test the application
     

  4. Return to MSVC

【故障诊断】【pytorch】基于CNN-LSTM故障分类的轴承故障诊断研究[西储大学数据](Python代码实现)内容概要:本文介绍了基于CNN-LSTM神经网络模型的轴承故障分类方法,利用PyTorch框架实现,采用西储大学(Case Western Reserve University)公开的轴承故障数据集进行实验验证。该方法结合卷积神经网络(CNN)强大的特征提取能力和长短期记忆网络(LSTM)对时序数据的建模优势,实现对轴承不同故障类型和严重程度的高精度分类。文中详细阐述了数据预处理、模型构建、训练流程及结果分析过程,并提供了完整的Python代码实现,属于典型的工业设备故障诊断领域深度学习应用研究。; 适合人群:具备Python编程基础和深度学习基础知识的高校学生、科研人员及工业界从事设备状态监测与故障诊断的工程师,尤其适合正在开展相关课题研究或希望复现EI级别论文成果的研究者。; 使用场景及目标:① 学习如何使用PyTorch搭建CNN-LSTM混合模型进行时间序列分类;② 掌握轴承振动信号的预处理与特征学习方法;③ 复现并改进基于公开数据集的故障诊断模型,用于学术论文撰写或实际工业场景验证; 阅读建议:建议读者结合提供的代码逐行理解模型实现细节,重点关注数据加载、滑动窗口处理、网络结构设计及训练策略部分,鼓励在原有基础上尝试不同的网络结构或优化算法以提升分类性能。
### 如何在MATLAB中使用Slider控件 在MATLAB中,`uicontrol` 函数可以用来创建各种类型的用户界面组件,其中包括 `slider` 控件。通过设置属性并编写回调函数,可以使 slider 的行为更加灵活和实用。以下是关于如何在 MATLAB 中使用 slider 组件的具体说明。 #### 创建 Slider 控件 可以通过 `uicontrol` 函数创建一个 slider 控件,并为其指定必要的属性。例如: ```matlab hSlider = uicontrol('Style', 'slider', ... 'Min', 0, ... 'Max', 100, ... 'Value', 50, ... % 初始值 'Position', [20 20 200 20], ... 'Callback', @sliderCallback); ``` 上述代码片段定义了一个水平方向的滑动条,其最小值为 0,最大值为 100,默认初始值为 50[^1]。 #### 设置 Slider 属性 除了基本的 `Min`, `Max`, 和 `Value` 外,还可以调整其他一些重要属性来增强用户体验: - **SliderStep**: 定义滑块移动时的大步长和小步长比例。 - **Enable**: 控制控件是否可用。 - **BackgroundColor**: 调整背景颜色以匹配整体 UI 设计风格。 示例配置如下所示: ```matlab set(hSlider, 'SliderStep', [0.01 0.1]); % 小步长占总范围的比例为 1%,大步长为 10% set(hSlider, 'Enable', 'on'); % 启用控件 set(hSlider, 'BackgroundColor', [0.8 0.8 0.8]); % 浅灰色背景 ``` #### 编写 Callback 函数 当用户拖动滑块时会触发关联的回调函数,在此函数内部可以根据当前滑块的位置执行特定逻辑。下面是一个简单的例子,它将滑块当前位置显示在一个可编辑文本框 (`editable text`) 中: ```matlab function sliderCallback(hObject, eventdata) currentValue = get(hObject, 'Value'); set(findobj(gcf, 'Tag', 'EditBox'), 'String', num2str(currentValue)); end ``` 在此基础上,如果希望进一步扩展功能,则可以引入更多复杂的计算或者绘图操作[^3]。 #### 实际案例分析 考虑这样一个场景——绘制一条直线 y = ax 并允许实时修改斜率 a 值。具体实现方式如下: 1. 初始化图形窗口; 2. 添加一个 slider 来调节系数 a; 3. 更新曲线数据集以便反映最新的 a 值; 完整脚本可能看起来像这样: ```matlab figure; axesHandle = axes(); lineHandle = plot(axesHandle, [], [], '-r'); % Create the slider control. sliderHandle = uicontrol('Style', 'slider',... 'Units','normalized',... 'Position',[0.1 0.05 0.8 0.05],... 'Min', -5,... 'Max', 5,... 'Value', 1,... 'Callback',{@updateLine,lineHandle}); function updateLine(src,eventdata,lineObj) slope = get(src,'Value'); xData = linspace(-10,10,100); yData = slope .* xData; set(lineObj,'XData',xData,'YData',yData); drawnow; % Ensure immediate visual feedback. end ``` 以上程序展示了如何利用 slider 动态改变图表中的线条斜率[^2]。 ---
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值